Home > Mobile >  How to get argument in action filter when the controller action has no corresponding argument?
How to get argument in action filter when the controller action has no corresponding argument?

Time:01-12

I am working on an ASP.NET Core 6 based web application. To avoid writing a lot of redundant code in my controllers, I implemented a class BaseController which all of my controllers inherit from. In that class, I overrided the OnActionExecutionAsync method to run the code which would otherwise be redundant in every controller. In this code, I need to access two arguments which I would otherwise have to pass to each controller action via its arguments like this: public async Task<ActionResult> ExampleAction([FromQuery(Name = "argument1")] Guid? argument1, [FromQuery(Name = "argument2")] Guid? argument2)

As long as I keep those arguments in every action, I can easily access them in the OnActionExecutionAsync method. However, I do not want to do it like this because it would require me to add the arguments to every single controller action while I do not even need them there. Now I have the problem that when I remove the arguments from the controller action, I can no longer access them via context.ActionArguments in the OnActionExecutionAsync method.

Is there any way how I can still access the arguments in this situation? I already found this question on SO which is very similar but the suggested solution to use actionContext.ControllerContext.RouteData.Values["tenant"] does not work in my case. There simply is no ControllerContext in ASP.NET Core 6 and context.RouteData.Values does not seem to contain the arguments I am looking for.

CodePudding user response:

You can access the query-string values using HttpContext.Request.Query. Here's an example:

var tenantValues = context.HttpContext.Request.Query["tenant"];

The type of tenantValues here is StringValues, which represents one or more values. If you know there's only going to be one value provided, you can treat it as a collection and use [0] or First(), for example, or just case it as string.

CodePudding user response:

You can use HttpContext property of ActionContext (which is ancestor of ActionExecutingContext) to access request query string values:

public override Task OnActionExecutionAsync(ActionExecutingContext actionContext, ActionExecutionDelegate next)
{
    StringValues values = actionContext.HttpContext.Request.Query["tenant"];
}
  •  Tags:  
  • Related