Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the default namespaces in MapHttpRoute?

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?

like image 901
jwanga Avatar asked Feb 22 '12 21:02

jwanga


People also ask

What is the default path call GET method in Web API?

The default route template for Web API is "api/{controller}/{id}".

Which of the following types of routing is supported in Web API?

Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API.

Which of the following declaration enables attribute routing in Web API core?

MapHttpAttributeRoutes() enables attribute routing which we will learn later in this section. The config. Routes is a route table or route collection of type HttpRouteCollection. The "DefaultApi" route is added in the route table using MapHttpRoute() extension method.

Which is optional element when you define route config in Web API?

Web API uses URI as “DomainName/api/ControllerName/Id” by default where Id is the optional parameter. If we want to change the routing globally, then we have to change routing code in register Method in WebApiConfig.


1 Answers

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.

like image 180
Shazwazza Avatar answered Sep 28 '22 18:09

Shazwazza