In the ASP. NET Web API, use the namespace (namespace) as the parameter for the route

Source: Internet
Author: User

The problem is that I want to use the same director name (Controller) in the Web API under different namespaces, but the Web API's default route (route) mechanism ignores the different namespaces, and if you do, you see the following prompt:

Multiple types were found that match the controller named "XXX". This can occur if multiple controllers are found for a route that provides services for this request ("{namespace}/{controller}/{action}"), and these controllers are defined with the same name but different namespaces (this is not supported).

in ASP. NET MVC, you can solve this problem by building a region (area), but the Web API does not have a region.

But the authorities have already given the solution, but are not directly integrated as part of the Web API. I don't know what to think.

Original link: http://blogs.msdn.com/b/webdev/archive/2013/03/08/using-namespaces-to-version-web-apis.aspx

The main idea is to re-implement a routing selector that identifies the namespace, and then replace the system's default routing selector. This namespace-selective organ has also been implemented for us and provides a complete sample of project demonstrations.

Code Link: http://aspnet.codeplex.com/SourceControl/changeset/view/dd207952fa86#Samples/WebApi/ Namespacecontrollerselector/namespacehttpcontrollerselector.cs

Add the implementation of this class to the project and replace it when initializing the Web API route, and when setting up the routing template, add the appropriate {namespace} parameters:

 Public Static classwebapiconfig{ Public Static voidRegister (httpconfiguration config) {config.        Maphttpattributeroutes (); Config. Services.replace (typeof(Ihttpcontrollerselector),Newnamespacehttpcontrollerselector (config)); Config. Routes.maphttproute (Name:"Defaultapi", Routetemplate:"{namespace}/{controller}/{action}"        ); }}

Finally, attach the official Namespacehttpcontrollerselector class implementation code (see the link above):

 Public classnamespacehttpcontrollerselector:ihttpcontrollerselector{Private Const stringNamespacekey ="namespace"; Private Const stringControllerkey ="Controller"; Private ReadOnlyhttpconfiguration _configuration; Private ReadOnlylazy<dictionary<string, httpcontrollerdescriptor>>_controllers; Private ReadOnlyhashset<string>_duplicates;  Publicnamespacehttpcontrollerselector (httpconfiguration config) {_configuration=config; _duplicates=Newhashset<string>(stringcomparer.ordinalignorecase); _controllers=Newlazy<dictionary<string, httpcontrollerdescriptor>>(initializecontrollerdictionary); }    Privatedictionary<string, httpcontrollerdescriptor>initializecontrollerdictionary () {varDictionary =Newdictionary<string, httpcontrollerdescriptor>(stringcomparer.ordinalignorecase); //Create a lookup table where key is "Namespace.controller". The value of "namespace" is the last//Segment of the full namespace. For example://MyApplication.Controllers.V1.ProductsController = "V1. Products "Iassembliesresolver Assembliesresolver =_configuration.        Services.getassembliesresolver (); Ihttpcontrollertyperesolver Controllersresolver=_configuration.        Services.gethttpcontrollertyperesolver (); ICollection<Type> controllertypes =controllersresolver.getcontrollertypes (Assembliesresolver); foreach(Type tinchcontrollertypes) {            varsegments =T.namespace.split (Type.delimiter); //for the dictionary key, strip "Controller" from the end of the type name. //This matches the behavior of Defaulthttpcontrollerselector.            varControllername = T.name.remove (T.name.length-DefaultHttpControllerSelector.ControllerSuffix.Length); varKey = String.Format (CultureInfo.InvariantCulture,"{0}. {1}", Segments[segments. Length-1], controllername); //Check for duplicate keys.            if(dictionary. Keys.contains (key)) {_duplicates.            ADD (key); }            Else{Dictionary[key]=NewHttpcontrollerdescriptor (_configuration, T.name, T); }        }        //Remove any duplicates from the dictionary, because these create ambiguous matches. //For example, the "Foo.V1.ProductsController" and "Bar.V1.ProductsController" both map to "v1.products".        foreach(stringSinch_duplicates) {Dictionary.        Remove (s); }        returndictionary; }    //Get A value from the route data, if present.    Private StaticT getroutevariable<t> (Ihttproutedata routedata,stringname) {        Objectresult =NULL; if(RouteData.Values.TryGetValue (Name, outresult)) {            return(T) result; }        return default(T); }     Publichttpcontrollerdescriptor Selectcontroller (httprequestmessage request) {Ihttproutedata Routedata=request.        Getroutedata (); if(Routedata = =NULL)        {            Throw Newhttpresponseexception (Httpstatuscode.notfound); }        //Get the namespace and controller variables from the route data.        stringNamespaceName = getroutevariable<string>(Routedata, Namespacekey); if(NamespaceName = =NULL)        {            Throw Newhttpresponseexception (Httpstatuscode.notfound); }        stringControllername = getroutevariable<string>(Routedata, Controllerkey); if(Controllername = =NULL)        {            Throw Newhttpresponseexception (Httpstatuscode.notfound); }        //Find a matching controller.        stringKey = String.Format (CultureInfo.InvariantCulture,"{0}. {1}", NamespaceName, controllername);        Httpcontrollerdescriptor Controllerdescriptor; if(_controllers. Value.trygetvalue (Key, outcontrollerdescriptor)) {            returnControllerdescriptor; }        Else if(_duplicates. Contains (key)) {Throw Newhttpresponseexception (Request. Createerrorresponse (Httpstatuscode.internalservererror,"multiple controllers were found the match this request.")); }        Else        {            Throw Newhttpresponseexception (Httpstatuscode.notfound); }    }     Publicidictionary<string, httpcontrollerdescriptor>getcontrollermapping () {return_controllers.    Value; }}

In the ASP. NET Web API, use the namespace (namespace) as the parameter for the route

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.