ASP.Net Web API 中基于属性的路由使用
2015-03-23 13:15
316 查看
原文地址:http://www.intstrings.com/ramivemula/articles/attribute-based-routing-in-asp-net-web-api/
我们大多数人已经知道我们在 WebApiConfig 文件中配置的 Web API 的传统路由概念。这种方法解决了大多数基本的路由问题,但是它将自定义路由的细粒度的控制和灵活性进行限制。属性基于路由是最受欢迎的 nuget 可以灵活地管理控制器/行动一级的路线。在本教程中,我们打算去看我们如何能得到的基本属性基于路由的作品。
在我们进入一些代码之前,让我第一次分享关于基于属性的路由和社区的贡献 — — http://weblogs.asp.net/scottgu/archive/2013/04/19/asp-net-web-api-cors-support-and-attribute-based-routing-improvements.aspx ScottGu 的最近的博客文章。让我们感谢蒂姆 · 麦考尔 — — http://attributerouting.net/ 为我们提供一个美丽的特征。
让我们开始与 Web API 模板创建一个新的 ASP.Net MVC4 项目。右键单击项目,选择管理 Nuget 程序包,搜索"AttributeRouting",从结果中安装 AttributeRouting (ASP.NET Web API) 。
下面为一些代码示例
using AttributeRouting; using AttributeRouting.Web.Http; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace MvcApplication1.Controllers {
// http://xxx/Products/GetEverything [RoutePrefix("Products")] public class ValuesController : ApiController { [GET("GetEverything")] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // http://xxx/Products/GetProduct/1 [GET("GetProduct/{id}")] public string Get(string id) { return "value1"; } } }这样能更方便的定义路由级别,如下的一些示例[GET("GetProductByName/{name=Merc}")]
public string GetByName(string name)
{
return name;
}[GET("GetProductByName/{name:alpha:length(4)=Merc}")]public string GetByName(string name){ return name;}
[GET("GetEverything", ActionPrecedence = 1)] [GET("Index")] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; }
[GET("GetProduct/{id}?{x}")] public string Get(string id) { return String.Format("Passed Id : {0}, Passed Querystring: {1}", id, System.Web.HttpContext.Current.Request.QueryString["x"].ToString()); }
http://xxx/my/Products/2?3
[RouteArea("My")] [RoutePrefix("Products")] public class ValuesController : ApiController
以上为一部分示例,可以看到,这样相当于自定义路径。
相关文章推荐
- ASP.NET Web API 2 中的属性路由使用(转载)
- 使用属性在 ASP.NET Web API 2 路由创建一个 REST API
- asp.net web api使用默认路由 put delete动作在IIS下受限
- ASP.NET WEB API 如何使用基于Post的方式传递多个值(二)
- 【Web API系列教程】2.3 — ASP.NET Web API 2中的属性路由
- [转]使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【八】——Web Api的安全性
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程
- Asp.Net Web API 2第八课——Web API 2中的属性路由
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【外传】——Attribute Routing
- 使用Route Prefix 使用属性路由 精通ASP-NET-MVC-5-弗瑞曼
- 运用路由约束 使用属性路由 精通ASP-NET-MVC-5-弗瑞曼
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【六】——实现资源间的关联
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【七】——实现资源的分页
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【八】——Web Api的安全性
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【九】——API变了,客户端怎么办?
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【开篇】【持续更新中。。。】
- 使用ASP.NET WEB API构建基于REST风格的服务实战系列教程(一)——使用EF6构建数据库及模型
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【二】——使用Repository模式构建数据库访问层
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【三】——Web Api入门