设置WebApi里面命名空间参数
在这种情况下:
如果没有特别处理,会报:
所以要像MVC中的控制器一下配置一个命名空间参数,webapi里面没有自带这个功能
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Dispatcher;
using AutoData.Utility; namespace AutoData
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
//config.HostNameComparisonMode = HostNameComparisonMode.Exact; config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
); config.Routes.MapHttpRoute(
name: "Admin Area Default",
routeTemplate: "api/admin/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional, namespaceName = "AutoData.Areas.Admin.Controllers" }
); config.Routes.MapHttpRoute(
name: "IndustryInsight Area Default",
routeTemplate: "Api/IndustryInsight/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
); config.Routes.MapHttpRoute(
name: "ComputeFormula Area Default",
routeTemplate: "Api/ComputeFormula/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional , namespaceName = "AutoData.Areas.ComputeFormula.Controllers"}
);
config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config));
}
}
}
最后一句设置,也可以配置在全局类里面:
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(GlobalConfiguration.Configuration));
功能是一样的
NamespaceHttpConrollerSelector类
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
using System.Web.Http.Routing; namespace AutoData.Utility
{
public class NamespaceHttpControllerSelector : IHttpControllerSelector
{
private const string NamespaceKey = "namespaceName";
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 - 1], controllerName); //旧版本
var key = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", t.Namespace.ToString(), 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;
}
}
}
对它进行了一点点的修改,
旧版本的命名空间选.号的最后一个
我设置的取全名命名空间
这样设置以后会发现一起没有设置命名空间的路由会发生错误,所有WebApiConfig里面的路由必须设置命名空间
http://www.cnblogs.com/nikyxxx/p/3356659.html
http://aspnet.codeplex.com/SourceControl/changeset/view/dd207952fa86#Samples/WebApi/NamespaceControllerSelector/NamespaceHttpControllerSelector.cs
http://www.osdo.net/article/2015/01/13/160.html
http://blog.csdn.net/starfd/article/details/41728655
设置WebApi里面命名空间参数的更多相关文章
- MVC5为WebAPI添加命名空间的支持
前言 默认情况下,微软提供的MVC框架模板中,WebAPI路由是不支持Namespace参数的.这导致一些比较大型的项目,无法把WebApi分离到单独的类库中. 本文将提供解决该问题的方案. 微软官方 ...
- asp.net MVC5为WebAPI添加命名空间的支持
前言 默认情况下,微软提供的MVC框架模板中,WebAPI路由是不支持Namespace参数的.这导致一些比较大型的项目,无法把WebApi分离到单独的类库中. 本文将提供解决该问题的方案. 微软官方 ...
- MVC5为WebAPI添加命名空间的支持1
前言 默认情况下,微软提供的MVC框架模板中,WebAPI路由是不支持Namespace参数的.这导致一些比较大型的项目,无法把WebApi分离到单独的类库中. 本文将提供解决该问题的方案. 微软官方 ...
- WebApi支持命名空间重名问题
using System;using System.Collections.Concurrent;using System.Collections.Generic;using System.Linq; ...
- Asp.Net Mvc4 Webapi Request获取参数
最近用mvc4中的WEBAPI,发现接收参数不是很方便,跟传统的request.querystring和request.form有很大区别,在网上搜了一大圈,各种方案都有,但不是太详细,于是跟踪Act ...
- 开发ASP.NET MVC设置统一的命名空间
当你创建一个全新的ASP.NET MVC专案之后,你想设置统一的命名空间,从可以下面几次入手. 首先设置专案的属性: 第二步,打开Views/Web.config文件,修改: 第三步,修改路由文件的命 ...
- qmake的使用(可设置c编译器flag参数)
本文由乌合之众 lym瞎编,欢迎转载 my.oschina.net/oloroso***还是先说一下当前的系统环境:Ubuntu 14.04 + Qt5.4如果没有安装过QT,可以安装下面几个qt软件 ...
- RHCE 系列(二):如何进行包过滤、网络地址转换和设置内核运行时参数
正如第一部分(“设置静态网络路由”)提到的,在这篇文章(RHCE 系列第二部分),我们首先介绍红帽企业版 Linux 7(RHEL)中包过滤和网络地址转换(NAT)的原理,然后再介绍在某些条件发生变化 ...
- Swift语言中为外部参数设置默认值可变参数常量参数变量参数输入输出参数
Swift语言中为外部参数设置默认值可变参数常量参数变量参数输入输出参数 7.4.4 为外部参数设置默认值 开发者也可以对外部参数设置默认值.这时,调用的时候,也可以省略参数传递本文选自Swift1 ...
随机推荐
- 微软 IIS HTTP.sys漏洞原理学习以及POC
零.MS15-034POC核心部分(参考巡风): socket.setdefaulttimeout(timeout) s = socket.socket(socket.AF_INET, socket. ...
- mysql 安装流程 兼容8.0.0以上版本 解决修改密码规则问题
背景介绍: 第一次安装mysql服务端,版本8.0.6 遇到了问题:1:不知道流程:2:8.0以上版本密码加密规则修改的解决方案: 1:下载mysql 服务端 https://dev.mysql. ...
- ios UITableView默认选中第一行
NSIndexPath *ip = [NSIndexPath indexPathForRow:0inSection:0]; [titleTableViewselectRowAtIndexPath:ip ...
- OC开发_Storyboard——Core Data
一 .NSManagedObjectContext 1.我们要想操作Core Data,首先需要一个NSManagedObjectContext2.那我们如何获得Context呢:创建一个UIMana ...
- Oracle下回滚rollback的使用
oracle中可以设置一个回滚点进行回滚 设置回滚名称 savepoint pointa ; 进行回滚 rollback to pointa; 如果期间有删除的数据就回来了
- backend community-driven web framework
kataras/iris: The fastest backend community-driven web framework on (THIS) Earth. HTTP/2, MVC and mo ...
- Online handwriting recognition using multi convolution neural networks
w可以考虑从计算机的“机械性.重复性”特征去设计“低效的”算法. https://www.codeproject.com/articles/523074/webcontrols/ Online han ...
- 我希望知道的关于Django的11件事(转)
英文原文:https://medium.com/cs-math/f29f6080c131 译文:http://my.oschina.net/chenlei123/blog/270672 两年前, 我开 ...
- linux 的nohup & 和daemon 总结(转)
add by zhj:守护进程貌似跟nohup + &方式启动的进程差不多.都可以实现与终端的无关联. 原文:http://blog.csdn.net/lovemdx/article/de ...
- java-信息安全(十八)java加密解密,签名等总结
一.基本概念 加密: 密码常用术语: 明文,密文,加密,加密算法,加密秘钥,解密,解密算法,解密秘钥, 密码分析:分析密文从而推断出明文或秘钥的过程 主动攻击:入侵密码系统,采用伪造,修改,删除等手段 ...