ASP.Net Web API 中基于属性的路由使用
来源:互联网 发布:aspen优化 编辑:程序博客网 时间:2024/05/17 06:18
原文地址: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;
}
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
以上为一部分示例,可以看到,这样相当于自定义路径。
0 0
- ASP.Net Web API 中基于属性的路由使用
- 使用属性在 ASP.NET Web API 2 路由创建一个 REST API
- 使用Nancy构建基于mono的ASP.NET Web API
- ASP.NET Web API Selfhost宿主环境中管道、路由
- ASP.NET Web API WebHost宿主环境中管道、路由
- OData - ASP.NET Web API 2 中Odata路由约定
- 【Web API系列教程】2.3 — ASP.NET Web API 2中的属性路由
- ASP.NET Web API 路由对象介绍
- 《Asp.Net Web Api 》-----路由机制
- ASP.NET Web API路由系统:Web Host下的URL路由
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【三】——Web Api入门
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程
- 基于Attribute的Web API路由设置
- 基于Attribute的Web API路由设置
- 使用 ASP.NET Web 窗体路由
- ASP.NET Web API框架揭秘:Web Host下的URL路由
- asp.net web api使用默认路由 put delete动作在IIS下受限
- 什么是类(class)成员函数
- IOS后台运行机制详解(二)
- Python中的OS模块
- cocos2dx C++调用java -- 字符串传递
- js装饰者模式
- ASP.Net Web API 中基于属性的路由使用
- 现在我给你两种选择,一学编程,二不学编程
- weakSelf的宏定义及用法
- matlab实现excel表格到Markdown表格
- jQuery超酷HTML DOM元素纸张3D折叠特效
- 常用数据结构--线性结构
- running bash commands in python
- 第一周项目二 长方体柱类
- 第3周项目4 考了语文数学的学生