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:
我有一个asp.net web api,使用属性在控制器上进行路由。在作用层上没有路径消耗。访问资源的途径是:
[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
我的问题是,当我想要创建一个搜索控制器时,我希望URL是
[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?
但这导致了一个错误:发现了与URL匹配的多个控制器类型。是否有可能在常规路径之前确定正确的匹配路径?
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.
从技术上讲,短语搜索可能是第一个控制器的有效ID,但是由于{ID}是guid,这是不可能的,因此我希望选择具有精确匹配路由的控制器。
1 个解决方案
#1
1
You can use Route constraints to do the job. For example you could constraint your ID route to accept only valid GUID's.
您可以使用路由约束来完成这项工作。例如,您可以限制您的ID路由以只接受有效的GUID。
Here is an ID controller that accepts only GUID strings in the URL:
这里是一个ID控制器,它只接受URL中的GUID字符串:
[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:
搜索控制器将匹配一个url,如“/ Search”。这是搜索控制器:
[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.
约束将防止路由器中的匹配冲突。
#1
1
You can use Route constraints to do the job. For example you could constraint your ID route to accept only valid GUID's.
您可以使用路由约束来完成这项工作。例如,您可以限制您的ID路由以只接受有效的GUID。
Here is an ID controller that accepts only GUID strings in the URL:
这里是一个ID控制器,它只接受URL中的GUID字符串:
[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:
搜索控制器将匹配一个url,如“/ Search”。这是搜索控制器:
[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.
约束将防止路由器中的匹配冲突。