Route parameters and several types of controllers

I have an asp.net web api using attributes for routing on controllers. There are no attriutes routes at the action level. Resource access route:

[Route("{id}"]
public MyApiController: ApiController
{
    public HttpResponseMessage Get(Guid id)
    { 
        // ...
    }
}

      

My problem is that when I want to create a search controller I would like the url to be

[Route("search")]

      

But this leads to an error: Multiple controller types were found that match the URL

. Is it possible to be sure that the correct route is chosen to the general?

Technically, the phrase search

might be a valid identifier for the first controller, but since it {id}

is a guideline, this will never be the case, so I would like to select a controller with an exact matching route.

+3


source to share


1 answer


You can use Route restrictions to complete the task . For example, you can restrict your ID route to only valid GUIDs.

Here is an ID controller that only accepts a URL GUID in a URL:

[System.Web.Http.Route("{id:guid}")]
public class MyApiController: ApiController
{
    public HttpResponseMessage Get(Guid id)
    {
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

      



The search controller will match the url eg "/search"

. Here's the search controller:

[System.Web.Http.Route("search")]
public class SearchController : ApiController
{
    public HttpResponseMessage Get()
    {
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

      

The constraints will prevent the router from negotiating conflicts.

+1


source







All Articles