路径参数和多种控制器类型 [英] Route parameters and multiple controller types

查看:49
本文介绍了路径参数和多种控制器类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个asp.net Web API,使用属性在控制器上进行路由.在操作级别上没有路由属性.访问资源的途径是:

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)
    { 
        // ...
    }
}

我的问题是,当我想创建搜索控制器时,我希望URL为

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

[Route("search")]

但这会导致错误:找到了多个与URL匹配的控制器类型.是否可以确保在通用路由之前选择了完全匹配的路由?

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?

从技术上讲,短语 search 可能是第一个控制器的有效ID,但是由于 {id} 是一个向导,所以永远不会这样,因此我希望选择具有完全匹配路线的控制器.

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路由以仅接受有效的GUID.

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

这里是一个ID控制器,它仅接受URL中的GUID字符串:

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);
    }
}

搜索控制器将与"/search" 之类的网址匹配.这是搜索控制器:

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.

这篇关于路径参数和多种控制器类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆