[英]How to get argument in action filter when the controller action has no corresponding argument?
[英]Web API: How to get a route parameter when controller action does not have corresponding argument
我們使用 Web API 2 構建多租戶應用程序。我們希望將租戶信息嵌入到 URL 中,以便每個請求都可以獲取它。 例如http://localhost/tenant1/api/test 。 我們添加了一個應該從請求中提取租戶的操作過濾器。 但是,它只有在控制器動作方法簽名有相應參數時才有效。
這是代碼:
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);
}
}
當控制器是這樣的時候它工作得很好:
[RoutePrefix("{tenant}")]
public class TestController : ApiController
{
[Route("api/test")]
public string Get(string tenant) // we don't need it here
{
return "hello";
}
}
tenant
將僅用於操作過濾器,因此將其添加到每個控制器方法似乎是一件愚蠢的事情。 我們希望該控制器是:
public string Get() {...}
當控制器動作沒有相應的參數時,有沒有辦法在動作過濾器中獲得該值?
在發布問題后找到答案:)
actionContext.ControllerContext.RouteData.Values["tenant"]
即使 action 沒有那個參數也能正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.