This article was written for ASP.NET MVC 4 RC (Release Candidate). If you are still using Beta version of ASP.NET MVC 4 then you have to read the previous article.

HttpControllerFactory was deleted in ASP.NET MVC 4 RC. Actually, it was replaced by two interfaces: IHtttpControllerActivator and IHttpControllerSelector.

Unfortunately DefaultHttpControllerSelector still doesn't support Areas by default. To support it you have to write your HttpControllerSelector from scratch. To be honest, I will derive my selector from DefaultHttpControllerSelector.

In this post I will show you how you can do it.

AreaHttpControllerSelector

First of all, you have to derive your class from DefaultHttpControllerSelector class:

public class AreaHttpControllerSelector : DefaultHttpControllerSelector
{
private readonly HttpConfiguration _configuration; public AreaHttpControllerSelector(HttpConfiguration configuration)
: base(configuration)
{
_configuration = configuration;
}
}

In the constructor mentioned above I called the base constructor and stored the HttpConfiguration. We will use it a little bit later.

My code will use two constants:

private const string ControllerSuffix = "Controller";
private const string AreaRouteVariableName = "area";

You can understand why we need first one by name. The second one contains the name of the variable which we will use to specify area name in Routes collection.

Somewhere we have to store all of the API controllers.

private Dictionary<string, Type> _apiControllerTypes;

private Dictionary<string, Type> ApiControllerTypes
{
get { return _apiControllerTypes ?? (_apiControllerTypes = GetControllerTypes()); }
} private static Dictionary<string, Type> GetControllerTypes()
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies(); var types = assemblies.SelectMany(a => a.GetTypes().Where(t => !t.IsAbstract && t.Name.EndsWith(ControllerSuffix) && typeof(IHttpController).IsAssignableFrom(t)))
.ToDictionary(t => t.FullName, t => t); return types;
}

Method GetControllerTypes takes all the API controllers types from all of your assemblies, and store it inside the dictionary, where the key is FullName of the type and value is the type itself.
Of course we will set this dictionary only once. And then just use it.

Now we are ready to implement one of the important method:

public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
return GetApiController(request) ?? base.SelectController(request);
}

In that method I try to take the HttpControllerDescriptor from method GetApiController and if it return null then call the base method.

And additional methods:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
private static string GetAreaName(HttpRequestMessage request)
{
    var data = request.GetRouteData();
 
    if (!data.Values.ContainsKey(AreaRouteVariableName))
    {
        return null;
    }
 
    return data.Values[AreaRouteVariableName].ToString().ToLower();
}
 
private Type GetControllerTypeByArea(string areaName, string controllerName)
{
    var areaNameToFind = string.Format(".{0}.", areaName.ToLower());
    var controllerNameToFind = string.Format(".{0}{1}", controllerName, ControllerSuffix);
 
    return ApiControllerTypes.Where(t => t.Key.ToLower().Contains(areaNameToFind) && t.Key.EndsWith(controllerNameToFind, StringComparison.OrdinalIgnoreCase))
            .Select(t => t.Value).FirstOrDefault();
}
 
private HttpControllerDescriptor GetApiController(HttpRequestMessage request)
{
    var controllerName = base.GetControllerName(request);
 
    var areaName = GetAreaName(request);
    if (string.IsNullOrEmpty(areaName))
    {
        return null;
    }
 
    var type = GetControllerTypeByArea(areaName, controllerName);
    if (type == null)
    {
        return null;
    }
 
    return new HttpControllerDescriptor(_configuration, controllerName, type);
}

Method GetAreaName just takes area name from HttpRequestMessage.

Method GetControllerTypeByArea are tries to find the controller in the ApiControllerTypes by full name of the controller where the full name contains area's name surrounded by "." (e.g. ".Admin.") and ends with controller name + controller suffix (e.g. UsersController).

And if a controller type found then method GetApiController will create and return back HttpControllerDescriptor.

So, my AreaHttpControllerSelector is ready to be registered in my application.

Registering AreaHttpControllerSelector

The next thing you have to do is to say to your application to use this controller selector instead of DefaultHttpControllerSelector. And fortunately it is really easy - just add one additional line to the end of Application_Start method in Glogal.asax file:

1
2
3
4
5
protected void Application_Start()
{
    // your default code
            GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector), new AreaHttpControllerSelector(GlobalConfiguration.Configuration));
}

That's all.

Using AreaHttpControllerSelector

If you did everything right, now you can forget about that "nightmare" code mentioned above. And just start to use it!

You have to add new HttpRoute to your AreaRegistration.cs file:

1
2
3
4
5
6
7
8
9
10
public override void RegisterArea(AreaRegistrationContext context)
{
    context.Routes.MapHttpRoute(
        name: "Admin_Api",
        routeTemplate: "api/admin/{controller}/{id}",
        defaults: new { area = "admin", id = RouteParameter.Optional }
    );
 
    // other mappings
}

Or just use one global route in your Global.asax like:

1
2
3
4
5
routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{area}/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

 

ASP.NET MVC 4 WebAPI. Support Areas in HttpControllerSelector的更多相关文章

  1. 给Asp.Net MVC及WebApi添加路由优先级

    一.为什么需要路由优先级 大家都知道我们在Asp.Net MVC项目或WebApi项目中注册路由是没有优先级的,当项目比较大.或有多个区域.或多个Web项目.或采用插件式框架开发时,我们的路由注册很可 ...

  2. 【转载】为ASP.NET MVC及WebApi添加路由优先级

    路由方面的: 转载地址:http://www.jb51.net/article/73417.htm Author:lijiao 这是一个对Asp.Net Mvc的一个很小的功能拓展,小项目可能不太需要 ...

  3. (转)ASP.NET Mvc 2.0 - 1. Areas的创建与执行

    转自:http://www.cnblogs.com/terrysun/archive/2010/04/13/1711218.html ASP.NET Mvc 2.0 - 1. Areas的创建与执行 ...

  4. AJAX跨域调用ASP.NET MVC或者WebAPI服务

    关于AJAX跨域调用ASP.NET MVC或者WebAPI服务的问题及解决方案 作者:陈希章 时间:2014-7-3 问题描述 当跨域(cross domain)调用ASP.NET MVC或者ASP. ...

  5. AJAX跨域调用ASP.NET MVC或者WebAPI服务的解决方案

    问题描述 当跨域(cross domain)调用ASP.NET MVC或者ASP.NET Web API编写的服务时,会发生无法访问的情况. 重现方式 使用模板创建一个最简单的ASP.NET Web ...

  6. ASP.NET MVC对WebAPI接口操作(添加,更新和删除)

    昨天<怎样操作WebAPI接口(显示数据)>http://www.cnblogs.com/insus/p/5670401.html 既有使用jQuery,也有使作HttpClient来从数 ...

  7. 关于AJAX跨域调用ASP.NET MVC或者WebAPI服务的问题及解决方案

      作者:陈希章 时间:2014-7-3 问题描述 当跨域(cross domain)调用ASP.NET MVC或者ASP.NET Web API编写的服务时,会发生无法访问的情况. 重现方式 使用模 ...

  8. ASP.NET MVC 4 WebAPI Simple Sample

    // Controllers.cs namespace Microshaoft.WebApi.Controllers { using Microshaoft.WebApi.Models; using ...

  9. Asp.Net MVC part6 WebAPI

    两种web服务SOAP风格:基于方法,产品是WebServiceREST风格:基于资源,产品是WebAPI可以返回json.xml类型的数据对于数据的增.删.改.查,提供相对的资源操作,按照请求的类型 ...

随机推荐

  1. APM 终端用户体验监控分析(上)

    一.前言 理解用户体验是从终端用户角度了解应用交付质量的关键,这是考量业务健康运转的潜在因素.捕获此类数据的方法各种各样,具体的实现途径由应用.基础设施架构以及管理者和管理过程决定. 二.终端用户监控 ...

  2. 2016年度 JavaScript 展望(上)

    [编者按]本文作者为资深 Web 开发者 TJ VanToll, TJ 专注于移动端 Web 应用及其性能,是<jQuery UI 实践> 一书的作者. 本文系 OneAPM 工程师编译呈 ...

  3. 导出含有图片的项目成jar文件后运行,图片不显示

    在编写完Java程序后,打包成Jar时发布,会发现找不到Jar文件中的图片和文本文件,其原因是程序中载入图片或文本文件时,使用了以当前工作路径为基准的方式来指定文件和路径.这与用户运行Jar包时的当前 ...

  4. zoj Fibonacci Numbers ( java , 简单 ,大数)

    题目 //f(1) = 1, f(2) = 1, f(n > 2) = f(n - 1) + f(n - 2) import java.io.*; import java.util.*; imp ...

  5. POJ 2891 Strange Way to Express Integers (解一元线性方程组)

    求解一元线性同余方程组: x=ri(mod ai) i=1,2,...,k 解一元线性同余方程组的一般步骤:先求出前两个的解,即:x=r1(mod a1)     1x=r2(mod a2)     ...

  6. 安装软件(名称不记得了)后,系统开机提示 visual studio just-in-time debugger窗口(WINDOWS错误提示框)

    出现这种情况,往往是因为原先安装有VS,后来因某些原因(比如:卸载)导致VS无法使用!!当系统中的有些软件出现错误时,会自动调用vs进行调试,但因为VS无法使用,就出现了visual studio j ...

  7. POJ 2101

    #include <iostream> #include <algorithm> #include <cmath> using namespace std; int ...

  8. App自适应

    http://blog.csdn.net/newjueqi/article/details/42779221

  9. BZOJ 1008: [HNOI2008]越狱 快速幂

    1008: [HNOI2008]越狱 Description 监狱有连续编号为1...N的N个房间,每个房间关押一个犯人,有M种宗教,每个犯人可能信仰其中一种.如果相邻房间的犯人的宗教相同,就可能发生 ...

  10. mysql之游标

    游标 行,也不存在每次一行地处理所有行的简单方法(相对于成批地处理它们).有时,需要在检索出来的行中前进或后退一行或多行.这就是使用游标的原因.游标( cursor)是一个存储在MySQL服务器上的数 ...