Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Route parameters and multiple controller types

I have a asp.net web api, using attributes for routing on the controllers. There are no route attriutes on the action level. The route for accessing a resource is:

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

My problem is that when I want to create a search controller, I'd like the URL to be

[Route("search")]

But this results in an error: Multiple controller types were found that match the URL. Is it possible to make sure the exact matching route is selected before the generic one?

Technically, the phrase search could be a valid ID for the first controller, but as {id} is a guid, this will never be the case, thus I'd like to select the controller with the exact matching route.

like image 491
Jørgen Avatar asked Jan 20 '26 04:01

Jørgen


1 Answers

You can use Route constraints to do the job. For example you could constraint your ID route to accept only valid GUID's.

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

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

The Search controller would match to an url like "/search". Here is the Search controller:

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

Constraints will prevent matching conflicts in the router.

like image 194
Faris Zacina Avatar answered Jan 22 '26 18:01

Faris Zacina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!