Question

My solution contains class library project as business library, and I have written a custom action filter in it.

public class SampleFilterAttribute : ActionFilterAttribute, IExceptionFilter
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var parameters =filterContext.ActionDescriptor.GetParameters();
        var currentAction = filterContext.ActionDescriptor;
    }

My requirement is now to pass some other parameters to OnActionExecuted function (like Username, description that I will save in database).

My controller action in MVC application project looks like:

 [SampleFilterAttribute]
    public ActionResult PurchaseRequisition(int? ID)
    {

So how can I pass some custom parameters to OnActionExecuted() Action Filter?

Was it helpful?

Solution

You can pass a parameter to your custom Filter Attribute via TempData, see below:

SampleFilterAttribute

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var actionDescriptor = filterContext.ActionDescriptor;
        var controllerName = actionDescriptor.ControllerDescriptor.ControllerName;
        var actionName = actionDescriptor.ActionName;
        var userName = filterContext.HttpContext.User.Identity.Name;
        var timeStamp = filterContext.HttpContext.Timestamp;

        var parameters = filterContext.RouteData.Values["id"]; 
        var description = filterContext.Controller.TempData["Description"];

        base.OnActionExecuted(filterContext);
    }

Action

    [SampleFilter]
    public ActionResult PurchaseRequisition(int? id)
    {
        TempData["Description"] = "This is Description";
        return View();
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top