MVC4.0 WebApi如何设置api支持namespace
2015-10-26 15:45
274 查看
1.自定义HttpControllerSelector
2.注册路由
这样我们就可以像areas一样使用webapi了
/// <summary> /// 设置api支持namespace /// </summary> public class NamespaceHttpControllerSelector : DefaultHttpControllerSelector { private const string NamespaceRouteVariableName = "namespace_name"; private readonly HttpConfiguration _configuration; private readonly Lazy<ConcurrentDictionary<string, Type>> _apiControllerCache; public NamespaceHttpControllerSelector(HttpConfiguration configuration) : base(configuration) { _configuration = configuration; _apiControllerCache = new Lazy<ConcurrentDictionary<string, Type>>( new Func<ConcurrentDictionary<string, Type>>(InitializeApiControllerCache)); } private ConcurrentDictionary<string, Type> InitializeApiControllerCache() { IAssembliesResolver assembliesResolver = this._configuration.Services.GetAssembliesResolver(); var types = this._configuration.Services.GetHttpControllerTypeResolver().GetControllerTypes(assembliesResolver).ToDictionary(t => t.FullName, t => t); return new ConcurrentDictionary<string, Type>(types); } public IEnumerable<string> GetControllerFullName(HttpRequestMessage request, string controllerName) { object namespaceName; var data = request.GetRouteData(); IEnumerable<string> keys = _apiControllerCache.Value.ToDictionary<KeyValuePair<string, Type>, string, Type>(t => t.Key, t => t.Value, StringComparer.CurrentCultureIgnoreCase).Keys.ToList(); if (!data.Values.TryGetValue(NamespaceRouteVariableName, out namespaceName)) { return from k in keys where k.EndsWith(string.Format(".{0}{1}", controllerName, DefaultHttpControllerSelector.ControllerSuffix), StringComparison.CurrentCultureIgnoreCase) select k; } string[] namespaces = (string[])namespaceName; return from n in namespaces join k in keys on string.Format("{0}.{1}{2}", n, controllerName, DefaultHttpControllerSelector.ControllerSuffix).ToLower() equals k.ToLower() select k; } public override HttpControllerDescriptor SelectController(HttpRequestMessage request) { Type type; if (request == null) { throw new ArgumentNullException("request"); } string controllerName = this.GetControllerName(request); if (string.IsNullOrEmpty(controllerName)) { throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound, string.Format("No route providing a controller name was found to match request URI '{0}'", new object[] { request.RequestUri }))); } IEnumerable<string> fullNames = GetControllerFullName(request, controllerName); if (fullNames.Count() == 0) { throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound, string.Format("No route providing a controller name was found to match request URI '{0}'", new object[] { request.RequestUri }))); } if (this._apiControllerCache.Value.TryGetValue(fullNames.First(), out type)) { return new HttpControllerDescriptor(_configuration, controllerName, type); } throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound, string.Format("No route providing a controller name was found to match request URI '{0}'", new object[] { request.RequestUri }))); } }
2.注册路由
public static class WebApiConfig { public static void Register(HttpConfiguration config) { //注册支持namespace的HttpControllerSelector,替换默认DefaultHttpControllerSelector config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(GlobalConfiguration.Configuration)); config.Routes.MapHttpRoute( name: "Phone", routeTemplate: "api/phone/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional, namespace_name = new string[] { "Amy.WebUI.Api.Phone" } } ); config.Routes.MapHttpRoute( name: "ApiDefault", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional, namespace_name = new string[] { "Amy.WebUI.Api" } } ); } }
这样我们就可以像areas一样使用webapi了
相关文章推荐
- 老李分享:什么是好战略
- [转载]android service 使用以及aidl使用
- UIViewController的生命周期
- Android开发的一些小细节和一些常用的小东西
- 081.Return Pointer Function 返回指针的函数
- Android Studio(一) 安装
- UED大全
- 【js】JSON.stringify 语法实例讲解
- 分页查询(转)
- 【图论训练】最小拓扑序
- 【iOS】The executable was signed with invalid entitlements.
- android开发很有用的工具网址
- Android之UI开源框架
- 深入剖析授权在WCF中的实现
- 082.Pointer Array 指针数组
- Thread和Runnable一些区别以及线程的同步
- 更好一点的Hello World
- Android Camera 系统架构源码分析(1)---->Camera的初始化
- Android Activity切换动画(解决back键后退失效问题)
- 正则表达式与文本格式化处理