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

ASP.NET Web API 2 中的特性路由的更多相关文章

  1. ASP.NET Web API 2 中的属性路由使用(转载)

    转载地址:ASP.NET Web API 2 中的属性路由使用

  2. ASP.NET Web API 2中的属性路由(Attribute Routing)

    如何启用属性路由并描述属性路由的各种选项? Why Attribute Routing? Web API的第一个版本使用基于约定的路由.在这种类型的路由中,您可以定义一个或多个路由模板,这些模板基本上 ...

  3. ASP.NET Web API 2.0新特性:Attribute Routing1

    ASP.NET Web API 2.0新特性:Attribute Routing[上篇] 对于一个针对ASP.NET Web API的调用请求来说,请求的URL和对应的HTTP方法的组合最终决定了目标 ...

  4. 【ASP.NET Web API教程】4.2 路由与动作选择

    原文:[ASP.NET Web API教程]4.2 路由与动作选择 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本系列教程,请先看前面的内容. 4.2 Routing ...

  5. Web API 2中的属性路由

    Web API 2中的属性路由 前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.ht ...

  6. 在ASP.NET Web API项目中使用Hangfire实现后台任务处理

    当前项目中有这样一个需求:由前端用户的一个操作,需要触发到不同设备的消息推送.由于推送这个具体功能,我们采用了第三方的服务.而这个服务调用有时候可能会有延时,为此,我们希望将消息推送与用户前端操作实现 ...

  7. Asp.Net Web API 2第八课——Web API 2中的属性路由

    前言 阅读本文之前,您也可以到Asp.Net Web API 2 系列导航进行查看 http://www.cnblogs.com/aehyok/p/3446289.html 路由就是Web API如何 ...

  8. ASP.NET Web API 2中的错误处理

    前几天在webapi项目中遇到一个问题:Controller构造函数中抛出异常时全局过滤器捕获不到,于是网搜一把写下这篇博客作为总结. HttpResponseException 通常在WebAPI的 ...

  9. [翻译]ASP.NET Web API 2 中的全局错误处理

    目录 已存在的选项 解决方案预览 设计原则 什么时候去用 方案详情 示例 附录: 基类详情 原文链接 Global Error Handling in ASP.NET Web API 2 由于翻译水平 ...

随机推荐

  1. 判断Ie浏览器

    ie8以下 if(!+[1,]) if(window.attachEvent){ alert("ie")}else if(window.addEventListener){aler ...

  2. Groovy basic

    1. print println "Hello Groovy!" you can use java in Groovy System.out.println("Hello ...

  3. MATLAB - 练习程序,求灰度图像均值、最大、最小数值

    clear all; close all; clc img=imread('lena.bmp'); figure; imshow(uint8(img)); [m n]=size(img); img_m ...

  4. iOS开发-xcdatamodeld文件 CoreData的介绍和使用,sqlite的使用

    CoreData的介绍和使用  源引:http://www.jianshu.com/p/d027090af00e CoreData是数据存储的一种方式,CoreData实质也是对SQLite的封装. ...

  5. python之urllib

    简单的web应用包括使用被称为url(统一资源定位器,uniform resource locator)的web地址 这个地址用来在web上定位一个文档,或调用一个CGI程序来为你的客户端产生一个文档 ...

  6. java实现smtp邮件发送

    一.准备工作 首先你需要已一个发送邮箱,一般的邮箱都有SMTP.POP3服务,比如QQ邮箱,登陆QQ邮箱开启SMTP服务,开启是服务器会提示你设置独立密码,这个密码是跟邮箱正常登陆的密码不同的,这个是 ...

  7. Python学习笔记- Python threading模块

    Python threading模块 直接调用 # !/usr/bin/env python # -*- coding:utf-8 -*- import threading import time d ...

  8. lvm snapshot(lvm 快照)

    lvm快照有多种实现方法,其中一种是COW(Copy-On-Write),不用停止服务或将逻辑卷设为只读就可以进行备份,当一个 snapshot创建的时候只是拷贝原始卷里的元数据,而不是物理上的数据, ...

  9. MySQL数据库指定字符集

    mysql 创建数据库时指定编码很重要,很多开发者都使用了默认编码,但是我使用的经验来看,制定数据库的编码可以很大程度上避免倒入导出带来的乱码问题. 我们遵循的标准是,数据库,表,字段和页面或文本的编 ...

  10. <T>的用法

    ///类型转换 template <class T1,class T2> vector<T2> ObjcetsSwap(vector<T1> objects) { ...