环境: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. php处理XML数据

    把XML转换成对象直接调用里面的属性 <?php$note=<<<XML<note><to>Tove</to><from>Jan ...

  2. SVN服务器更改ip地址客户端怎么设置(转载)

    SVN 服务器 IP 地址修改后,客户端对服务器的连接可以采用以下的方法重定位: 1. 如果客户端工具是TortoiseSVN,直接在工作副本上右键,选择TortoiseSVN->relocat ...

  3. vb.net winform exe 接参数

    找到如下文件 -\WindowsApplication1\My Project\Application.Designer.vb <Global.System.Diagnostics.Debugg ...

  4. 设置phpcms v9黄页模块作为首页方法

    如果我们根据需要,想把黄页作为单独的网站,我们可以用模块化安装,并且首页设置,那么仿站网就说说详细的步骤.首先,我们需要安装最新版本的phpcms V9其次,下载黄页模块,然后进行根目录的替换.再次, ...

  5. android逆向分析之smali语法

    一 .smali数据类型 1.Dalvik字节码 Davlik字节码中,寄存器都是32位的,能够支持任何类型,64位类型(Long/Double)用2个连续的寄存器表示: Dalvik字节码有两种类型 ...

  6. android studio - 修改logcat颜色字体

     修改logcat 颜色 (1) 在Android Studio 菜单栏 打开 Preferences -> Editer -> Colors & Fonts -> Andr ...

  7. iptables 使用

    原文链接 本文介绍25个常用的iptables用法.如果你对iptables还不甚了解,可以参考上一篇iptables详细教程:基础.架构.清空规则.追加规则.应用实例,看完这篇文章,你就能明白ipt ...

  8. js模块化规范AMD、CMD、CommonJS...

    1. AMD 1.1 什么是AMD? AMD 英文名 Asynchronous Module Definition ,中文名 异步模块定义 .这是一个浏览器模块化开发的规范. 由于浏览器环境执行环境的 ...

  9. 完工尚需绩效指数 TCPI

    转自:http://www.cnblogs.com/allenblogs/archive/2010/12/09/1901404.html TCPI To Complete Performance In ...

  10. 1.2.3 Task and Back Stack - 任务和回退堆

    一个应用通常包含多个Activities.每个activity的设计应该围绕着某种指定类型的action,如果这样做了,用户就可以执行该action,也可以用它来开启另外的activity.例如,邮件 ...