如何在ASP.NET Web API 2中获取自定义RouteTemplate属性的值?

时间:2014-11-07 19:17:36

标签: rest asp.net-web-api2 asp.net-web-api-routing

我想创建一个如下所示的自定义路由配置:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{location}/{id}",
    defaults: new { id = RouteParameter.Optional }

我需要一个location属性,该属性将包含一个整数id,表示特定API用户的位置。

之后,我将在控制器级别添加一个自定义属性,如:

[VerifyLocation]
public class SomeController : ApiController

对传递给每个端点的位置值进行一些后台验证。这意味着我需要能够获得location属性的整数值。

我知道您可以使用Route属性来自定义您的路线,但事情是希望这样做,而不必在我的所有终点上放置[Route("api/{location:id}/{id:int"}]

我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

(如果有人偶然发现这个问题)

一种方法是通过ActionFilterAttribute

public class VerifyLocation : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var routeData = actionContext.RequestContext.RouteData;

        var location = routeData.Values["location"];

        // Do your thing here

        base.OnActionExecuting(actionContext);
    }
}