在这种情况下:

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

所以要像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. Python 导入与注册

    背景 最近一直学习写一个POC扫描框架,但是不知道如何下手,正巧因为一些需要有朋友在研究POCSuite的实现原理,顺面蹭一些知识点,补一补Python基础的不足,为以后编写POC框架打地基. 导入 ...

  2. 索引原理 B tree

    数据库原理之-索引 背景介绍: 用数据库的时候经常有几个疑问: 1:为啥通过加索引就能提升数据的查询料率? 2:为啥加多了索引会导致增删改的效率变低? 3:为啥有的人能用好有的人用不好? 这些问题我们 ...

  3. ios 使用ASIHTTPRequest来检查版本更新

    - (void) alertWithTitle: (NSString *)_title_ msg:(NSString *)msg delegate:(id)_delegate cancelButton ...

  4. 从零打造在线网盘系统之Hibernate配置O/R映射

    欢迎浏览Java工程师SSH教程从零打造在线网盘系统系列教程,本系列教程将会使用SSH(Struts2+Spring+Hibernate)打造一个在线网盘系统,本系列教程是从零开始,所以会详细以及着重 ...

  5. 170807、intellij idea maven集成lombok实例

    简介: lombok 通过简单注解方式简化java代码.(如消除实体对象的get/setter方法.日志对象声明等...) 安装步骤: 1.选择支持注解处理:Settings-->Build-- ...

  6. Oracle之归档模式与非归档模式

    归档模式和非归档模式 在DBA部署数据库之初,必须要做出的最重要决定之一就是选择归档模式(ARCHIVELOG)或者非 归档模式(NOARCHIVELOG )下运行数据库.我们知道,Oracle 数据 ...

  7. 后缀树 & 后缀数组

    后缀树: 字符串匹配算法一般都分为两个步骤,一预处理,二匹配. KMP和AC自动机都是对模式串进行预处理,后缀树和后缀数组则是对文本串进行预处理. 后缀树的性质: 存储所有 n(n-1)/2 个后缀需 ...

  8. #pragma预处理命令详解

    #pragma预处理命令 #pragma可以说是C++中最复杂的预处理指令了,下面是最常用的几个#pragma指令: #pragma comment(lib,"XXX.lib") ...

  9. Augmented reality in natural scenes

    Augmented reality in natural scenes (Iryna Gordon and David Lowe)2006年关于AR的研究成果 项目主页 http://www.cs.u ...

  10. Python大数据:jieba 中文分词,词频统计

    # -*- coding: UTF-8 -*- import sys import numpy as np import pandas as pd import jieba import jieba. ...