Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get action parameter on OnActionExecuting

Using .NET core MVC C#

I have a controller as:

[ServiceFilter(typeof(MyCustomFilter))]
public class HomeController : Controller
{
    public IActionResult Index(string type)
    {

    }
}

In my filter I want to get the string value of type as it's being passed as a query string.

And my filter as:

  [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class MyCustomFilter: ActionFilterAttribute
{
   public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
          //this is always null
           string id = filterContext.RouteData.Values["type"].ToString();
    }
}

Anything I am missing here? Because I have read few posts and they have mentioned the above to do that.

like image 417
aman Avatar asked Mar 07 '23 05:03

aman


2 Answers

For parameters passed in query string use:

string id = filterContext.Request.Query["type"];
like image 127
Racil Hilan Avatar answered Mar 21 '23 03:03

Racil Hilan


I believe you could use something like the following. I use something similar to the below in a logging filter. The log filter code is below as well. You could also iterate the collection as well.

string id = filterContext.ActionParameters["Type"];

Iterating through all parameters and aggregating them into a log string that is eventually written to a file.

logString = filterContext.ActionParameters.Aggregate(logString, (current, p) => current + (p.Key + ": " + p.Value + Environment.NewLine));
like image 36
Jammin411 Avatar answered Mar 21 '23 04:03

Jammin411