How do I set the default namespaces in MapHttpRoute?

拟墨画扇 提交于 2020-01-10 07:52:06

问题


With the standard MapRoute method a can pass a string collection representing the namespaces in which to search for my controller. This seems to have disappeared from MapHttpRoute. How does one define the default namespaces using the new API routing?


回答1:


We had this problem with the Umbraco core so we created our own IHttpControllerSelector, the source code can be found here:

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

You can also install nuget package WebAPIContrib which contains NamespaceHttpControllerSelector.

To register this you can do this on app startup:

GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector),
    new NamespaceHttpControllerSelector(GlobalConfiguration.Configuration));

The implementation is pretty straight forward and only deals with routes that have the "Namespaces" datatoken set which you have to manually set since the MapHttpRoute doesn't support this. Example:

var r = routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
r.DataTokens["Namespaces"] = new string[] {"Foo"};

The implementation also only caches controllers found with duplicate names since the underlying default implementation removes duplicates from it's cache.




回答2:


That feature does not exist currently.




回答3:


Although the feature does not exist at this moment, you can however do this by implementing your own IHttpControllerSelector.

This blog article digs a bit into the details: ASP.NET Web API: Using Namespaces to Version Web APIs




回答4:


You don't need to set default namespaces with Web API, it will search for controllers in all namespaces in the referenced assemblies (public types with name ending by 'Controller' which implement IHttpController).




回答5:


Before the MapHttpRoute Factory call add

System.Web.Mvc.ControllerBuilder.Current.DefaultNamespaces.Add("Namespace.Full.Controllers"); 


来源:https://stackoverflow.com/questions/9403450/how-do-i-set-the-default-namespaces-in-maphttproute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!