Route parameters and multiple controller types

别说谁变了你拦得住时间么 提交于 2020-03-01 20:58:32

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/26584113/route-parameters-and-multiple-controller-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!