根据路由值(命名空间)选择ASP.NET Web API Controller

时间:2016-04-05 08:54:41

标签: c# asp.net asp.net-mvc asp.net-mvc-4 asp.net-web-api

我正在尝试将各种Web API插件添加到我的MVC网站。复制和粘贴API文件的DLL允许我使用默认路由调用适当的服务方法 - hostname / api / {controller} / {id},但是当我有相同名称但位于不同位置的控制器时,它会抛出错误( DLL,命名空间)。错误消息是这样的(这是正常的):

  

找到了多个与名为' Names'的控制器匹配的类型。如果为此请求提供服务的路由(' api / {controller} / {id}')发现多个控制器定义了相同名称但名称不同的命名空间(不受支持),则会发生这种情况。要求'姓名'找到了以下匹配的控制器:ApiExt.NamesController ApiExt1.NamesController

我有相同的"姓名"控制器在不同的DLL(命名空间)ApiExt,ApiExt1。

我已经找到一个类似的主题来根据API版本选择控制器 - http://shazwazza.com/post/multiple-webapi-controllers-with-the-same-name-but-different-namespaces/,但这不是我需要的。我需要根据路由值选择控制器(名称空间),如下所示:

  

主机名/ API / {命名空间} / {控制器} / {ID}

我相信这绝对是可能的,但我不熟悉重写MVC控制器选择器(实现IHttpControllerSelector)。

有什么建议吗?

谢谢。

2 个答案:

答案 0 :(得分:3)

你绝对可以做到这一点。您需要通过实现IHttpControllerSelector来编写自己的Controller Selector。有关详细的逐步说明,请参阅this链接。

答案 1 :(得分:0)

描述解决方案的博客帖子https://blogs.msdn.microsoft.com/webdev/2013/03/07/asp-net-web-api-using-namespaces-to-version-web-apis/并不包含完整的代码,并且与过去提供的代码有着错误的链接。

这是一个提供班级的blob,原文来自Umbraco

https://github.com/WebApiContrib/WebAPIContrib/blob/master/src/WebApiContrib/Selectors/NamespaceHttpControllerSelector.cs

完整列表以防其被删除:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;

namespace WebApiContrib.Selectors
{
    //originally created for Umbraco https://github.com/umbraco/Umbraco-CMS/blob/7.2.0/src/Umbraco.Web/WebApi/NamespaceHttpControllerSelector.cs
    //adapted from there, does not recreate HttpControllerDescriptors, instead caches them
    public class NamespaceHttpControllerSelector : DefaultHttpControllerSelector
    {
        private const string ControllerKey = "controller";
        private readonly HttpConfiguration _configuration;
        private readonly Lazy<HashSet<NamespacedHttpControllerMetadata>> _duplicateControllerTypes;

        public NamespaceHttpControllerSelector(HttpConfiguration configuration)
            : base(configuration)
        {
            _configuration = configuration;
            _duplicateControllerTypes = new Lazy<HashSet<NamespacedHttpControllerMetadata>>(InitializeNamespacedHttpControllerMetadata);
        }

        public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
        {
            var routeData = request.GetRouteData();
            if (routeData == null || routeData.Route == null || routeData.Route.DataTokens["Namespaces"] == null)
                return base.SelectController(request);

            // Look up controller in route data
            object controllerName;
            routeData.Values.TryGetValue(ControllerKey, out controllerName);
            var controllerNameAsString = controllerName as string;
            if (controllerNameAsString == null)
                return base.SelectController(request);

            //get the currently cached default controllers - this will not contain duplicate controllers found so if
            // this controller is found in the underlying cache we don't need to do anything
            var map = base.GetControllerMapping();
            if (map.ContainsKey(controllerNameAsString))
                return base.SelectController(request);

            //the cache does not contain this controller because it's most likely a duplicate, 
            // so we need to sort this out ourselves and we can only do that if the namespace token
            // is formatted correctly.
            var namespaces = routeData.Route.DataTokens["Namespaces"] as IEnumerable<string>;
            if (namespaces == null)
                return base.SelectController(request);

            //see if this is in our cache
            var found = _duplicateControllerTypes.Value.FirstOrDefault(x => string.Equals(x.ControllerName, controllerNameAsString, StringComparison.OrdinalIgnoreCase) && namespaces.Contains(x.ControllerNamespace));
            if (found == null)
                return base.SelectController(request);

            return found.Descriptor;
        }

        private HashSet<NamespacedHttpControllerMetadata> InitializeNamespacedHttpControllerMetadata()
        {
            var assembliesResolver = _configuration.Services.GetAssembliesResolver();
            var controllersResolver = _configuration.Services.GetHttpControllerTypeResolver();
            var controllerTypes = controllersResolver.GetControllerTypes(assembliesResolver);

            var groupedByName = controllerTypes.GroupBy(
                t => t.Name.Substring(0, t.Name.Length - ControllerSuffix.Length),
                StringComparer.OrdinalIgnoreCase).Where(x => x.Count() > 1);

            var duplicateControllers = groupedByName.ToDictionary(
                g => g.Key,
                g => g.ToLookup(t => t.Namespace ?? String.Empty, StringComparer.OrdinalIgnoreCase),
                StringComparer.OrdinalIgnoreCase);

            var result = new HashSet<NamespacedHttpControllerMetadata>();

            foreach (var controllerTypeGroup in duplicateControllers)
            {
                foreach (var controllerType in controllerTypeGroup.Value.SelectMany(controllerTypesGrouping => controllerTypesGrouping))
                {
                    result.Add(new NamespacedHttpControllerMetadata(controllerTypeGroup.Key, controllerType.Namespace,
                        new HttpControllerDescriptor(_configuration, controllerTypeGroup.Key, controllerType)));
                }
            }

            return result;
        }

        private class NamespacedHttpControllerMetadata
        {
            private readonly string _controllerName;
            private readonly string _controllerNamespace;
            private readonly HttpControllerDescriptor _descriptor;

            public NamespacedHttpControllerMetadata(string controllerName, string controllerNamespace, HttpControllerDescriptor descriptor)
            {
                _controllerName = controllerName;
                _controllerNamespace = controllerNamespace;
                _descriptor = descriptor;
            }

            public string ControllerName
            {
                get { return _controllerName; }
            }

            public string ControllerNamespace
            {
                get { return _controllerNamespace; }
            }

            public HttpControllerDescriptor Descriptor
            {
                get { return _descriptor; }
            }
        }
    }
}

然后只需将命名空间标记添加到路径

route.DataTokens["Namespaces"] = new string[] {"Foo.Controllers"};

通过缓存也可以提高生产效率。