您的位置:首页 > 编程语言 > ASP

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

以上为一部分示例,可以看到,这样相当于自定义路径。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐