route attribute in webapi

安装:Install-Package Microsoft.AspNet.WebApi.WebHost

引用:System.Web.Http.HttpConfigurationExtensions

配置:

webapi2

public static class WebApiConfig

{

    public static void Register(HttpConfiguration config)

    {

        // Attribute routing.

        config.MapHttpAttributeRoutes();



        // Convention-based routing.

        config.Routes.MapHttpRoute(

            name: "DefaultApi",

            routeTemplate: "api/{controller}/{id}",

            defaults: new { id = RouteParameter.Optional }

        );

    }

}

webapi1

protected void Application_Start()

{

    // WARNING - Not compatible with attribute routing.

    //WebApiConfig.Register(GlobalConfiguration.Configuration);

      GlobalConfiguration.Configure(WebApiConfig.Register);

}

使用:

public class OrdersController : ApiController

{

    [Route("customers/{customerId}/orders")]

    [HttpGet]

    public IEnumerable<Order> FindOrdersByCustomer(int customerId) { ... }

}

tips

  • {}中的变量名和方法参数名匹配
  • 没有设置Route属性的方法使用默认路由
  • [AcceptVerbs("MKCOL")] 可以指定非标准谓词
  • RoutePrefix
    [RoutePrefix("api/books")]
    
    public class BooksController : ApiController
    
    {
    
        // GET api/books
    
        [Route("")]
    
        public IEnumerable<Book> Get() { ... }
    
    
    
        // GET api/books/5
    
        [Route("{id:int}")]
    
        public Book Get(int id) { ... }
    
    
    
        // POST api/books
    
        [Route("")]
    
        public HttpResponseMessage Post(Book book) { ... }
    
    
    
        // GET /api/authors/1/books
    
        [Route("~/api/authors/{authorId:int}/books")]
    
        public IEnumerable<Book> GetByAuthor(int authorId) { ... }
    
    }
  • 约束参数
    [Route("users/{id:int:min(1)}")]
    
    public User GetUserById(int id) { ... }
    
    //{x:regex(^\d{3}-\d{3}-\d{4}$)}
    
    //{x:range(10,50)}
    
    //{x:alpha}
    自定义约束
    //定义
    
    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;
    
        }
    
    }
    
    //注册
    
    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}")]
    
    public HttpResponseMessage GetNonZero(int id) { ... }
  • 可选参数和默认值
    public class BooksController : ApiController
    
    {
    
        [Route("api/books/locale/{lcid:int?}")]
    
        public IEnumerable<Book> GetBooksByLocale(int lcid = 1033) { ... }
    
    }
    
    
    
    
    
    public class BooksController : ApiController
    
    {
    
        [Route("api/books/locale/{lcid:int=1033}")]
    
        public IEnumerable<Book> GetBooksByLocale(int lcid) { ... }
    
    }
  • Routs name
    public class BooksController : ApiController
    
    {
    
        [Route("api/books/{id}", Name="GetBookById")]
    
        public BookDto GetBook(int id) 
    
        {
    
            // Implementation not shown...
    
        }
    
    
    
        [Route("api/books")]
    
        public HttpResponseMessage Post(Book book)
    
        {
    
            // Validate and add book to database (not shown)
    
    
    
            var response = Request.CreateResponse(HttpStatusCode.Created);
    
    
    
            // Generate a link to the new book and set the Location header in the response.
    
            string uri = Url.Link("GetBookById", new { id = book.BookId });
    
            response.Headers.Location = new Uri(uri);
    
            return response;
    
        }
    
    }
  • RouteOrder
    解析路由的顺序,默认order是0,越小越先,越精确越先
    [RoutePrefix("orders")]
    
    public class OrdersController : ApiController
    
    {
    
        [Route("{id:int}")] // constrained parameter
    
        public HttpResponseMessage Get(int id) { ... }
    
    
    
        [Route("details")]  // literal
    
        public HttpResponseMessage GetDetails() { ... }
    
    
    
        [Route("pending", RouteOrder = 1)]
    
        public HttpResponseMessage GetPending() { ... }
    
    
    
        [Route("{customerName}")]  // unconstrained parameter
    
        public HttpResponseMessage GetByCustomer(string customerName) { ... }
    
    
    
        [Route("{*date:datetime}")]  // wildcard
    
        public HttpResponseMessage Get(DateTime date) { ... }
    
    }
    
    
    
    //order
    
    orders/details
    
    orders/{id}
    
    orders/{customerName}
    
    orders/{*date}
    
    orders/pending

     

 

link:http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

你可能感兴趣的:(attribute)