环境:VS2012 .net 4.0

参考:

http://aspnet.codeplex.com/SourceControl/changeset/view/dd207952fa86#Samples/WebApi/NamespaceControllerSelector/NamespaceHttpControllerSelector.cs

http://www.cnblogs.com/xwgli/p/4457628.html

想在WebApi中对Api进行分类管理,各类下可能存在同名的Api,对Controller,可以在注册路由时指定namespace,但WebApi不支持。

目前国内对这块的需求好像不是特别大,只有一篇文章介绍了如何自动对多区域的Api进行注册。

搜索MSDN,发现官方早已给出了解决方法:将此类的实现加入到项目中,并在初始化 Web API 路由时进行替换,在设置路由模板的时候,加入相应的 {namespace} 参数即可。

以下是我的实验过程。

1.为api建立独立的目录。

eg:

Apis/Admin

Apis/Public

2.分另添加一个MemberApi做为试验

3.在App_Start中增加一个类,代码如下,直接Copy即可

    public class NamespaceHttpControllerSelector : IHttpControllerSelector
{
private const string NamespaceKey = "namespace";
private const string ControllerKey = "controller"; private readonly HttpConfiguration _configuration;
private readonly Lazy<Dictionary<string, HttpControllerDescriptor>> _controllers;
private readonly HashSet<string> _duplicates; public NamespaceHttpControllerSelector(HttpConfiguration config)
{
_configuration = config;
_duplicates = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
_controllers = new Lazy<Dictionary<string, HttpControllerDescriptor>>(InitializeControllerDictionary);
} private Dictionary<string, HttpControllerDescriptor> InitializeControllerDictionary()
{
var dictionary = new Dictionary<string, HttpControllerDescriptor>(StringComparer.OrdinalIgnoreCase); // Create a lookup table where key is "namespace.controller". The value of "namespace" is the last
// segment of the full namespace. For example:
// MyApplication.Controllers.V1.ProductsController => "V1.Products"
IAssembliesResolver assembliesResolver = _configuration.Services.GetAssembliesResolver();
IHttpControllerTypeResolver controllersResolver = _configuration.Services.GetHttpControllerTypeResolver(); ICollection<Type> controllerTypes = controllersResolver.GetControllerTypes(assembliesResolver); foreach (Type t in controllerTypes)
{
var segments = t.Namespace.Split(Type.Delimiter); // For the dictionary key, strip "Controller" from the end of the type name.
// This matches the behavior of DefaultHttpControllerSelector.
var controllerName = t.Name.Remove(t.Name.Length - DefaultHttpControllerSelector.ControllerSuffix.Length); var key = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", segments[segments.Length - ], controllerName); // Check for duplicate keys.
if (dictionary.Keys.Contains(key))
{
_duplicates.Add(key);
}
else
{
dictionary[key] = new HttpControllerDescriptor(_configuration, t.Name, t);
}
} // Remove any duplicates from the dictionary, because these create ambiguous matches.
// For example, "Foo.V1.ProductsController" and "Bar.V1.ProductsController" both map to "v1.products".
foreach (string s in _duplicates)
{
dictionary.Remove(s);
}
return dictionary;
} // Get a value from the route data, if present.
private static T GetRouteVariable<T>(IHttpRouteData routeData, string name)
{
object result = null;
if (routeData.Values.TryGetValue(name, out result))
{
return (T)result;
}
return default(T);
} public HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
IHttpRouteData routeData = request.GetRouteData();
if (routeData == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
} // Get the namespace and controller variables from the route data.
string namespaceName = GetRouteVariable<string>(routeData, NamespaceKey);
if (namespaceName == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
} string controllerName = GetRouteVariable<string>(routeData, ControllerKey);
if (controllerName == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
} // Find a matching controller.
string key = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", namespaceName, controllerName); HttpControllerDescriptor controllerDescriptor;
if (_controllers.Value.TryGetValue(key, out controllerDescriptor))
{
return controllerDescriptor;
}
else if (_duplicates.Contains(key))
{
throw new HttpResponseException(
request.CreateErrorResponse(HttpStatusCode.InternalServerError,
"Multiple controllers were found that match this request."));
}
else
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
} public IDictionary<string, HttpControllerDescriptor> GetControllerMapping()
{
return _controllers.Value;
}
}

4.修改WebApiConfig.cs内容

    public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{namespace}/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
); config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config));
}
}

让WebApi支持Namespace的更多相关文章

  1. MVC4.0 WebApi如何设置api支持namespace

    1.自定义HttpControllerSelector /// <summary> /// 设置api支持namespace /// </summary> public cla ...

  2. WebApi支持命名空间重名问题

    using System;using System.Collections.Concurrent;using System.Collections.Generic;using System.Linq; ...

  3. 让Asp.Net WebAPI支持OData查询,排序,过滤。

    让Asp.Net WebAPI支持OData后,就能支持在url中直接输入排序,过滤条件了. 一.创建Asp.Net WebAPI项目: 二.使用NuGet安装Asp.Net WebAPI 2.2和O ...

  4. 让Asp.Net WebAPI支持OData查询,排序,过滤。(转)

    出处:http://www.cnblogs.com/liuzhendong/p/4233380.html 让Asp.Net WebAPI支持OData后,就能支持在url中直接输入排序,过滤条件了. ...

  5. 让Asp.net mvc WebAPI 支持OData协议进行分页查询操作

    这是我在用Asp.net mvc WebAPI 支持 OData协议 做分页查询服务时的 个人拙笔. 代码已经开发到oschina上.有兴趣的朋友可以看看,欢迎大家指出不足之处. 看过了园子里的几篇关 ...

  6. webapi支持跨域访问

    写在前面 在实际应用中,跨域请求还是比较常见的,如何上接口直接支持跨域的访问呢? demo 场景项目A有个接口用来获取用户列表,现在项目b也有个功能需要加载用户列表.这两个项目在两个域名下,至少端口好 ...

  7. asp.net webapi支持跨域

    1.Install-Package Microsoft.AspNet.WebApi.Cors 2. using System.Web.Http; namespace WebService {     ...

  8. Session配置之WebApi支持

    1.在WebApiConfig中建立建立HttpControllerHandler和HttpControllerRouteHandler 并覆写它 public class SessionRouteH ...

  9. WebAPI支持Session

    1.在App_Start/WebApiConfig.cs中建立建立HttpControllerHandler和HttpControllerRouteHandler 并覆写它: public class ...

随机推荐

  1. Selenium自動化測試(Python+VS2013)-基礎篇-環境安裝

    Python+VS2013環境安裝 http://www.cnblogs.com/aehyok/p/3986168.html PTVS: http://microsoft.github.io/PTVS ...

  2. 点滴积累【C#】---C#实现上传word以流形式保存到数据库和读取数据库中的word文件。

    本文修改来源:http://www.cnblogs.com/zmgdpg/archive/2005/03/31/129758.html 效果: 数据库: 思路: 首先保存word到数据库:获取上传文件 ...

  3. [python小记]使用lxml修改xml文件,并遍历目录

    这次的目的是遍历目录,把目标文件及相应的目录信息更新到xml文件中.在经过痛苦的摸索之后,从python自带的ElementTree投奔向了lxml.而弃用自带的ElementTree的原因就是,na ...

  4. url中的查询字符串的参数解析

    <script> // 查询字符串函数location.search;"?q=javascript" function getQueryStringArgs(){ // ...

  5. WEB前端面试题 分别使用2个、3个、5个DIV画出一个大的红十字

    <!DOCTYPE html> <!--两个DIV--> <html> <body> <div style="width:100%;he ...

  6. [转]ubuntu安装gcc

    Ubuntu缺省情况下,并没有提供C/C++的编译环境,因此还需要手动安装. 如果单独安装gcc以及g++比较麻烦,幸运的是,为了能够编译Ubuntu的内核,Ubuntu提供了一个build-esse ...

  7. href中使用相对路径访问上级目录的方法

    项目ProjectXXX目录如下: WebContent> hello.jsp Folder1> foo.jsp Folder2> foo2.jsp 在foo.jsp中访问hello ...

  8. python 练习题1--打印三位不重复数字

    题目:有四个数字:1.2.3.4,能组成多少个互不相同且无重复数字的三位数?各是多少? 程序分析:可填在百位.十位.个位的数字都是1.2.3.4.组成所有的排列后再去 掉不满足条件的排列. 程序源代码 ...

  9. 跟着百度学PHP[14]-PDO的预处理语句1

    预处理语句有以下两个特点: 1.效率高 2.安全性好 为什么说预处理语句效率高呢? 预处理语句就好比一个模板,比如下面的一串插入语句: insert into admin(id,username,pa ...

  10. 做过的自定义 View

    做过的自定义 View android view custom 音频条状图 需求 详细设计 具体实现 音频条状图 需求 音频图 最终效果类似于音频图中的条状图 只是效果模拟,并不监听真实的音频 条的宽 ...