在这种情况下:

如果没有特别处理,会报:

所以要像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里面命名空间参数的更多相关文章

  1. MVC5为WebAPI添加命名空间的支持

    前言 默认情况下,微软提供的MVC框架模板中,WebAPI路由是不支持Namespace参数的.这导致一些比较大型的项目,无法把WebApi分离到单独的类库中. 本文将提供解决该问题的方案. 微软官方 ...

  2. asp.net MVC5为WebAPI添加命名空间的支持

    前言 默认情况下,微软提供的MVC框架模板中,WebAPI路由是不支持Namespace参数的.这导致一些比较大型的项目,无法把WebApi分离到单独的类库中. 本文将提供解决该问题的方案. 微软官方 ...

  3. MVC5为WebAPI添加命名空间的支持1

    前言 默认情况下,微软提供的MVC框架模板中,WebAPI路由是不支持Namespace参数的.这导致一些比较大型的项目,无法把WebApi分离到单独的类库中. 本文将提供解决该问题的方案. 微软官方 ...

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

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

  5. Asp.Net Mvc4 Webapi Request获取参数

    最近用mvc4中的WEBAPI,发现接收参数不是很方便,跟传统的request.querystring和request.form有很大区别,在网上搜了一大圈,各种方案都有,但不是太详细,于是跟踪Act ...

  6. 开发ASP.NET MVC设置统一的命名空间

    当你创建一个全新的ASP.NET MVC专案之后,你想设置统一的命名空间,从可以下面几次入手. 首先设置专案的属性: 第二步,打开Views/Web.config文件,修改: 第三步,修改路由文件的命 ...

  7. qmake的使用(可设置c编译器flag参数)

    本文由乌合之众 lym瞎编,欢迎转载 my.oschina.net/oloroso***还是先说一下当前的系统环境:Ubuntu 14.04 + Qt5.4如果没有安装过QT,可以安装下面几个qt软件 ...

  8. RHCE 系列(二):如何进行包过滤、网络地址转换和设置内核运行时参数

    正如第一部分(“设置静态网络路由”)提到的,在这篇文章(RHCE 系列第二部分),我们首先介绍红帽企业版 Linux 7(RHEL)中包过滤和网络地址转换(NAT)的原理,然后再介绍在某些条件发生变化 ...

  9. Swift语言中为外部参数设置默认值可变参数常量参数变量参数输入输出参数

    Swift语言中为外部参数设置默认值可变参数常量参数变量参数输入输出参数 7.4.4  为外部参数设置默认值 开发者也可以对外部参数设置默认值.这时,调用的时候,也可以省略参数传递本文选自Swift1 ...

随机推荐

  1. executeQuery、executeUpdate 和 execute

    Statement 接口提供了三种执行 SQL 语句的方法:executeQuery.executeUpdate 和 execute.使用哪一个方法由 SQL 语句所产生的内容决定. 1. Resul ...

  2. c# SQL Server数据库操作-数据适配器类:SqlDataAdapter

    SqlDataAdapter类主要在MSSQL与DataSet之间执行数据传输工具,本节将介绍如何使用SqlDataAdapter类来填充DataSet和MSSQL执行新增.修改..删除等操作. 功能 ...

  3. java的Result类

    import org.apache.commons.lang.StringUtils; import java.io.Serializable;import java.util.HashMap;imp ...

  4. 云笔记类APP推荐

    一.思绪收集类 Google Keep - 记事和清单 - Google Play 上的应用 注:谷歌 Keep 是最方便的收集思绪 APP 了.卡片视图,反应迅速,流畅,UI 漂亮,功能齐全,唯一不 ...

  5. P2750 贰五语言Two Five USACO5.5 记忆化搜索

    正解:记搜+逼近 解题报告: 神仙题预警,,, 我真滴觉得还是挺难的了,,, 大概说下思路趴QAQ 首先我们要知道逼近法是什么! 逼近法,有点像二分的思路,以这题为例举个eg 假如它给了个数字k.我们 ...

  6. 完全用nosql轻松打造千万级数据量的微博系统(转)

    原文:http://www.cnblogs.com/imxiu/p/3505213.html 其实微博是一个结构相对简单,但数据量却是很庞大的一种产品.标题所说的是千万级数据量 也并不是一千万条微博信 ...

  7. python pip源配置

    一.Linux版本: linux的文件存放在:~/.pip/pip.conf 二.windows版本: 在用户文件夹下创建pip目录,并在pip目录下创建pip.ini文件(%HOME%\pip\pi ...

  8. (2.1)DDL增强功能-数据类型、同义词、分区表

    1.数据类型 (1)常用数据类型 1.整数类型 int 存储范围是-2,147,483,648到2,147,483,647之间的整数,主键列常设置此类型. (每个数值占用 4字节) smallint ...

  9. JS操作符转化数字

    在Node.js源代码里,随处可见使用各种符号处理字符串为数字的.可能由于不同人编写,使用的风格也各有不同. 基本上有下面几种. 将字符串转化为数字 + 将一个数字的字符串转化为数字很简单的一种做法就 ...

  10. 前端基础(jQuery)

    jquery: JS Bootstrap jquery: write less do more jquery对象: Jquery.方法 ======= $.方法 jquery的基础语法:$(selec ...