Fork me on GitHub

ASP.NET Web API 2 中的特性路由

ASP.NET MVC 5.1 开始已经支持基于特性的路由(http://attributerouting.net),ASP.NET WEB API 2 同时也支持了这一特性。

启用特性路

由只需要在webapiconfig设置

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.EnableSystemDiagnosticsTracing();
            // Web API routes[设置特性路由]
            config.MapHttpAttributeRoutes();

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

使用RoutePrefix特性

[RoutePrefix("orders")] 
public class OrdersController : ApiController 
{ 
    [Route("{id}")] 
    public Order Get(int id) { } 
    [Route("{id}/approve")] 
    public Order Approve(int id) { } 
}
使用特性路由可以更简洁的定义你的URL(RoutePrefix特性定义的前缀还可以带参数变量)
public class MoviesController : ApiController 
{ 
    [Route("movies")] 
    public IEnumerable<Movie> Get() { } 
    [Route("actors/{actorId}/movies")] 
    public IEnumerable<Movie> GetByActor(int actorId) { } 
    [Route("directors/{directorId}/movies")] 
    public IEnumerable<Movie> GetByDirector(int directorId) { } 
}

特性路由同时提供了一些基于参数约定,默认值等设置

//Optional parameter
[Route("people/{name?}")]
//Default value
[Route("people/{name=Dan}")]
//Constraint: Alphabetic characters only. 
[Route("people/{name:alpha}")]

路由约束

可以通过"{参数变量名称:约束}"来约束路由中的参数变量

[Route("users/{id:int}"]
public User GetUserById(int id) { ... }

[Route("users/{name}"]
public User GetUserByName(string name) { ... }

可选参数及其默认值

[Route("api/{id:int?}")]
public IEnumerable<T> Get(int id = 8){}

ASP.NET Web API内置约束包括

{x:alpha} 约束大小写英文字母
{x:bool}
{x:datetime}
{x:decimal}
{x:double}
{x:float}
{x:guid}
{x:int}
{x:length(6)}
{x:length(1,20)} 约束长度范围
{x:long}
{x:maxlength(10)}
{x:min(10)}
{x:range(10,50)}
{x:regex(正则表达式)}

可以为一个参数变量同时设置多个约束

[Route("api/{id:int:min(1)}")]

自定义约束

实现IHttpRouteConstraint接口,可自定义约束规则。实现一个不能为0的约束

public class NonZeroConstraint : IHttpRouteConstraint
{
    public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName,   IDictionary<string, object> values, HttpRouteDirection routeDirection)
    {
        object value;
        if (values.TryGetValue(parameterName, out value) && value != null)
        {
            long longValue;
            if (value is long)
            {
                longValue = (long)value;
                return longValue != 0;
            }
            string valueString = Convert.ToString(value, CultureInfo.InvariantCulture);
            if (Int64.TryParse(valueString, NumberStyles.Integer,    CultureInfo.InvariantCulture, out longValue))
            {
                return longValue != 0;
            }
        }
        return false;
    }
}

在WebApiConfig中注册自定义约束

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        var constraintResolver = new DefaultInlineConstraintResolver();
        constraintResolver.ConstraintMap.Add("nonzero", typeof(NonZeroConstraint));
        config.MapHttpAttributeRoutes(constraintResolver);
    }
}

使用自定义约束
[Route("{id:nonzero}")]

Refer:
Attribute Routing in Web API 2
http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
What's New in ASP.NET Web API 2.1
http://www.asp.net/web-api/overview/releases/whats-new-in-aspnet-web-api-21
visual-studio-2013 overview
http://www.asp.net/visual-studio/overview/2013/release-notes

posted @ 2014-10-23 15:17  花儿笑弯了腰  阅读(540)  评论(0编辑  收藏  举报