We build multi-tenancy application with Web API 2. We want to embed tenant info into the URL so that every request can get it. Eg http://localhost/tenant1/api/test . We added an action filter that should extract tenant from the request. However, it works only when controller action method signature has corresponding parameter.
Here is the code:
public class ValidationFilter : ActionFilterAttribute
{
public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
// works only if controller action has that argument
var tenant = actionContext.ActionArguments["tenant"];
Console.Out.WriteLine("tenant = {0}", tenant);
return base.OnActionExecutingAsync(actionContext, cancellationToken);
}
}
It works well when controller is like that:
[RoutePrefix("{tenant}")]
public class TestController : ApiController
{
[Route("api/test")]
public string Get(string tenant) // we don't need it here
{
return "hello";
}
}
The tenant
is going to be used only in action filter, so adding it to each and every controller method seems to be a silly thing. We want that controller to be:
public string Get() {...}
Is there any way to obtain that value in action filter when controller action does not have a corresponding argument?
Found answer just after posting the question :)
actionContext.ControllerContext.RouteData.Values["tenant"]
just works even when action does not have that argument.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.