【问题标题】:Multiple GET's in Web API calling wrong actionWeb API 中的多个 GET 调用错误的操作
【发布时间】:2013-11-26 17:46:34
【问题描述】:

我有一个Web API,如下所示...

public class LeaguesController : ApiController
{
    //api/Leagues/active/1
    //api/Leagues/complete/1
    //api/Leagues/both/1
    [GET("api/Leagues/{type}/{id}")]
    public List<Competition> Get([FromUri]int id, 
                                [FromUri]CompetitionManager.MiniLeagueType type)
    {
        return CompetitionManager.GetUsersMiniLeagues(id, true, type);
    }

    //api/Leagues/GetMiniLeagueTable/3
    [GET("api/Leagues/GetMiniLeagueTable/{id}")]
    public List<SportTableRow> GetMiniLeagueTable([FromUri]int id)
    {
        return SportManager.GetMiniLeagueTable("", id).TableRows;
    }
}

当我调用第一个方法Get 时,它工作正常。 当我使用 fiddler 或 Chrome REST Client 调用第二种方法GetMiniLeagueTable 时,出现以下错误:

{ 消息:“请求无效。” MessageDetail: "参数 字典包含不可为空的参数“类型”的空条目 为方法输入“CompetitionManager+MiniLeagueType” 'System.Collections.Generic.List`1[竞争] Get(Int32, MiniLeagueType)' 在'LeaguesController' 中。可选参数必须是 引用类型、可为空的类型或被声明为可选项 参数。” }

我正在使用AttributeRouting 来装饰方法,但这似乎不起作用。在我介绍 MiniLeagueType 之前它运行良好。

有没有人遇到过这个问题,或者你能指出我哪里出错了吗?

【问题讨论】:

  • 你怎么称呼它。有一些东西不应该是 null 传递为 null

标签: c# asp.net-web-api asp.net-web-api-routing attributerouting


【解决方案1】:

我认为原因是这个网址:api/Leagues/GetMiniLeagueTable/3。这个 url 匹配两个路由,因为它可以被解释为:api/Leagues?type=GetMiniLeagueTable&amp;id=3。但它无法将GetMiniLeagueTable 转换为CompetitionManager.MiniLeagueType 值,因此会引发错误。

你应该制定更具体的路由,例如api/Leagues/GetCompetitions/{type}/{id},以防止url匹配2个或更多不同的路由。

另一种可能性是反转您的操作顺序,因为如果 url 不匹配,它将检查第一个操作的路线,然后再进行下一个操作。

【讨论】:

  • 我不知道反转动作会做到这一点,但现在它是有道理的......这已经奏效了!
【解决方案2】:

看起来 url: /api/Leagues/GetMiniLeagueTable/3 将匹配两条路线。

假设它匹配第一个路由,那么它将无法将 GetMiniLeagueTable 转换为 CompetitionManager.MiniLeagueType,除非这是一个有效的枚举值。

你的第二条路线可能需要先测试,只有当它与 url 不匹配时,才尝试第二条。

我自己没有使用过属性路由(尽管我在最新的 web api 中使用过类似的属性路由)我猜ActionPrecedence 会有所帮助。

试试

[GET("api/Leagues/{type}/{id}", ActionPrecedence = 2)]

[GET("api/Leagues/GetMiniLeagueTable/{id}", ActionPrecedence = 1)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-17
    • 2016-04-08
    • 1970-01-01
    • 2015-05-01
    • 2017-04-19
    • 2016-07-31
    相关资源
    最近更新 更多