aman
aman

Reputation: 6242

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.

Upvotes: 7

Views: 7698

Answers (3)

Alex from Jitbit
Alex from Jitbit

Reputation: 60642

In .NET Core it's ActionArguments now.

string type = filterContext.ActionArguments["type"];

P.S. I wonder why they keep renaming stuff just for the sake of renaming it. Darn.

Upvotes: 2

Jammin411
Jammin411

Reputation: 418

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));

Upvotes: 5

Racil Hilan
Racil Hilan

Reputation: 25351

For parameters passed in query string use:

string id = filterContext.Request.Query["type"];

Upvotes: 5

Related Questions