How do I set the default namespaces in MapHttpRoute?

后端 未结 5 440
没有蜡笔的小新
没有蜡笔的小新 2020-12-25 10:57

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 MapHtt

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-25 11:52

    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.

提交回复
热议问题