简体   繁体   English

Web API 2属性路由冲突

[英]Web API 2 Attribute Routing Clash

I'm having issues getting my head around how route selection works. 我在选择路线的工作方式时遇到问题。 I have two route attributes set which are clashing with each other. 我设置了两个相互冲突的路由属性。 They Are 他们是

[Route("{apikey}/Parent/{parentID}/Children/ChildrenDataFormat")]
[Route("{apikey}/Parent/{parentID}/{dataSelectionTypeA}/{dataSelectionTypeB}")]

The first route's last two parts are hard coded and will never change. 第一条路线的最后两部分经过硬编码,永远不会更改。 The second route will bind into the method parameters. 第二条路线将绑定到方法参数中。

If I remove the second route then the first route works fine but otherwise I get a 404. I presume the Route Matching is seeing a Guid followed by "Parent" and then ignoring the fact that "Children" and "ChildrenDataFormat" should be present and instead seeing 3 things follow so route 2 is a match. 如果我删除第二条路线,那么第一条路线可以正常工作,但否则我得到404。我认为路线匹配会看到一个Guid,然后是“ Parent”,然后忽略了“ Children”和“ ChildrenDataFormat”应该存在的事实,并且而是看到3件事,所以路线2是匹配的。

If this a correct assumption and is there an obvious fix to make this work? 如果这是一个正确的假设,并且有明显的解决方案可以使这项工作奏效?

Oli 奥利

Since both your routes are attribute routes, they have no implicit order since both of them have the same number of path segments they both match leading to ambiguity. 由于这两个路由都是属性路由,因此它们没有隐式顺序,因为它们都具有相同数量的路径段,它们都匹配,从而导致歧义。

The solution is to differentiate between them, what you did was to add constraints to only one of the routes match, another solution is to use order so first the more specific route (the one ending with /Children/ChildrenDataFormat). 解决方案是区分它们,您所做的是仅对其中一条路由添加约束,另一种解决方案是使用顺序,因此首先使用更具体的路由(以/ Children / ChildrenDataFormat结尾的路由)。

Here is a simplistic example that shows order and how route values are being captures 这是一个简单的示例,显示了顺序以及如何捕获路线值

public class ValuesController : ApiController
{
    [Route("api/values/MyName", Order = 1)]
    [Route("api/values/{name}", Order = 2)]
    public string Get()
    {
        object nameObj;
        Request.GetRouteData().Values.TryGetValue("name", out nameObj);

        if (nameObj != null)
        {
            // came from second route
            return "Route is {name} and name was: " + (string) nameObj;
        }
        else
        {
            return "Route is MyName so no name value is available";
        }
    }
}

I'm still not sure what the exact issue was but I've managed to fix it by adding route constraints to all my variables. 我仍然不确定确切的问题是什么,但是我设法通过向所有变量添加路由约束来解决此问题。 IE my routes now look like IE浏览器我的路线现在看起来像

[Route("{apikey:guid}/Parent/{parentID:guid}/Children/ChildrenDataFormat")]
[Route("{apikey:guid}/Parent/{parentID:guid}/{dataSelectionTypeA:guid}/{dataSelectionTypeB:guid}")]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM