MVC,控制器中的两个 get 方法使用 Route
MVC, Two get methods in controller using Route
我正在尝试使用 Route 创建两个具有不同参数的 get 方法。
在我的数据库中,我有一个包含两列的 table:EventId 和 CategoryId。
我想return在url中使用EventId的情况下的所有匹配列表,例如:api/Match/5,在另一种情况下使用CategoryId用于url,例如:api/Match/425D750E-56BD-412C-8A48-38C2FBE5B24C.
在下面显示的我的 MatchController 设置中,具有 EventId 的方法工作正常,但具有 Guid CategoryId 的方法 return 是一个错误请求 (400) 和以下错误消息:
The parameters dictionary contains a null entry for parameter 'eventId' of non-nullable type 'System.Int32' for method 'System.Web.Http.IHttpActionResult GetMatchRecord(Int32)' in 'Nybroe.FightPlan.Web.Api.MatchController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
看起来它对每种情况都使用相同的方法。尽管我用 Route[].
指定了它
我是不是 Route[] 设置有问题?我也尝试在每个方法中完全删除 Route[],但结果仍然相同。
比赛控制器:
// GET api/Match/CategoryId
[Route("api/Match/{CategoryId}")]
[ResponseType(typeof(MatchRecord))]
public IHttpActionResult GetMatchRecord(Guid id)
{
var matches = db.Matches.Where(record => record.CategoryId == id).ToList();
if (matches == null)
{
return NotFound();
}
return Ok(matches);
}
// GET api/Match/EventId
[Route("api/Match/{EventId}")]
[ResponseType(typeof(MatchRecord))]
public IHttpActionResult GetMatchRecord(int eventId)
{
var matches = db.Matches.Where(record => record.EventId == eventId).ToList();
if (matches == null)
{
return NotFound();
}
return Ok(matches);
}
您可以使用路由约束:
尝试:
[Route("api/Match/{id:guid}")]
和
[Route("api/Match/{eventId:int}")]
我正在尝试使用 Route 创建两个具有不同参数的 get 方法。 在我的数据库中,我有一个包含两列的 table:EventId 和 CategoryId。
我想return在url中使用EventId的情况下的所有匹配列表,例如:api/Match/5,在另一种情况下使用CategoryId用于url,例如:api/Match/425D750E-56BD-412C-8A48-38C2FBE5B24C.
在下面显示的我的 MatchController 设置中,具有 EventId 的方法工作正常,但具有 Guid CategoryId 的方法 return 是一个错误请求 (400) 和以下错误消息:
The parameters dictionary contains a null entry for parameter 'eventId' of non-nullable type 'System.Int32' for method 'System.Web.Http.IHttpActionResult GetMatchRecord(Int32)' in 'Nybroe.FightPlan.Web.Api.MatchController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
看起来它对每种情况都使用相同的方法。尽管我用 Route[].
指定了它我是不是 Route[] 设置有问题?我也尝试在每个方法中完全删除 Route[],但结果仍然相同。
比赛控制器:
// GET api/Match/CategoryId
[Route("api/Match/{CategoryId}")]
[ResponseType(typeof(MatchRecord))]
public IHttpActionResult GetMatchRecord(Guid id)
{
var matches = db.Matches.Where(record => record.CategoryId == id).ToList();
if (matches == null)
{
return NotFound();
}
return Ok(matches);
}
// GET api/Match/EventId
[Route("api/Match/{EventId}")]
[ResponseType(typeof(MatchRecord))]
public IHttpActionResult GetMatchRecord(int eventId)
{
var matches = db.Matches.Where(record => record.EventId == eventId).ToList();
if (matches == null)
{
return NotFound();
}
return Ok(matches);
}
您可以使用路由约束:
尝试:
[Route("api/Match/{id:guid}")]
和
[Route("api/Match/{eventId:int}")]