使用默认的{controller} / {id}路由和{controller} / {action} / {id}路由时与路由冲突

问题描述 投票:0回答:1

我设置了以下路线;

RouteTable.Routes.MapHttpRoute(
   name: "ActionApi",
   routeTemplate: "api/{controller}/{action}/{id}",
   defaults: new { id = RouteParameter.Optional });

RouteTable.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = System.Web.Http.RouteParameter.Optional },
    constraints: null,
    handler: new WebApiMessageHandler(GlobalConfiguration.Configuration));

和以下控制器设置;

public class GetFileController : ApiController
{
    [HttpGet]
    public HttpResponseMessage Get(string id)
    {
        return Request.CreateResponse(HttpStatusCode.OK);
    }
}

我在这里的问题是这个网址

/api/GetFile/id_is_a_string

返回此错误;

<Error>
    <Message>
        No HTTP resource was found that matches the request URI /api/GetFile/id_is_a_string.
    </Message>
    <MessageDetail>
        No action was found on the controller 'GetFile' that matches the name 'id_is_a_string'.
    </MessageDetail>
</Error>

有什么办法可以避免它不认为字符串参数实际上是动作名称?

我知道我可以将请求网址更改为;

/api/GetFile?id=id_is_a_string

但是此路由更改会影响我已经设置的许多其他控制器,并且真的不希望浏览所有内容以将其切换为以这种方式发送请求。

如果我重新排序路由,它似乎可以正常工作,但是对于我希望在其中具有多个端点的新控制器,我会收到此错误;

ExceptionMessage=Multiple actions were found that match the request:

新控制器

public class GettingThingsController : ApiController
    {

        [HttpPost]
        public IHttpActionResult GetPeople()
        {
             return Ok();
        }

        [HttpPost]
        public IHttpActionResult GetProducts()
        {
            return Ok();
        }
    }

反正有实现我所需要的一切吗?!

asp.net-mvc asp.net-web-api asp.net-mvc-routing
1个回答
0
投票

您可以尝试使用Regex指定参数:

routeTemplate: "api/{controller}/{action:regex([a-z]{1}[a-z0-9_]+)}/{id:regex([0-9]+)}",

routeTemplate: "api/{controller}/{id:regex([0-9]+)}",

这些正则表达式在Route属性中起作用。您可以在RouteTable映射中对其进行测试。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.