我有一个 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/