c# - Web API 中的多个 GET 调用错误操作

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

我有一个 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 时,出现以下错误:

{ Message: "The request is invalid." MessageDetail: "The parameters dictionary contains a null entry for parameter 'type' of non-nullable type 'CompetitionManager+MiniLeagueType' for method 'System.Collections.Generic.List`1[Competition] Get(Int32, MiniLeagueType)' in 'LeaguesController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter." }

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

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

最佳答案

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

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

另一种可能性是反转您的操作顺序,因为如果 url 不匹配,它会在执行下一个操作之前检查第一个操作的路线。

关于c# - Web API 中的多个 GET 调用错误操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19965409/

相关文章:

c# - 多个 Controller 上的属性路由匹配请求的 url

c# - 使用ListBox存储多条数据

c# - 在 C# 的方法中返回 FileStream 是否安全?

c# - 如何在 ASP.NET Web API Core 应用程序上使用 QUARTZ 实现调度程序?

c# - 在 ASP.NET Web Api C# 中通过流发送和接收大文件

c# - ASP MVC WebApi 调用返回错误 'not found'

asp.net-mvc - 带有 urlEncoded 部分的 WebApi 路由

c# - 使用 WordProcessingDocument 时如何删除 XMLSchemaReference?

C# - 使用选中/未选中运算符的自定义显式转换

c# - 保持 Form 实例打开的任务?