我有一个名为Issues的模型,该模型的ID和严重性属性是整数,还有一个Issue Controller,该控制器应处理GET请求并按严重性返回所有Issue。由于Dotnet API不支持相同的参数类型(例如int),我该怎么做?
我尝试使用不同的方法名称,例如Get()
和GetBySeverity(int severity)
,但出现了模棱两可的异常。
这是我的控制器
[Route("api/[controller]")]
[ApiController]
public class IssuesController : ControllerBase
{
[HttpGet(Name="issues")]
public IEnumerable<Issue> GetAllIssues() {
IssueService service = new IssueService();
return service.GetIssues();
}
[HttpGet]
public IEnumerable<Issue> GetBySeverity([FromQuery(Name="severity")]int severity)
{
IssueService service = new IssueService();
return service.GetIssuesBySeverity(severity);
}
}
这些是我要开发的api
/api/issues/
和
/api/issues/?severity=1
答案 0 :(得分:0)
像这样
//GET api/issues/5
[HttpGet("{id}")]
public Issue GetByRoute([FromRoute(Name="id")] int id)
{
IssueService service = new IssueService();
return service.GetIssueById(id);
}
[HttpGet()]
public Issue GetByQuery([FromQuery(Name="severity")] int severityId)
{
IssueService service = new IssueService();
return service.GetIssueById(severityId);
}
答案 1 :(得分:0)
存在一个含糊的引用,因为这两个动作都是HttpGet
,并且路由引擎无法决定选择哪个路由或您要选择的路由。
Web Api控制器使用HttpVerbs而不是操作/方法名称(例如MVC)进行路由。
我会使用Attribute routing with Http[Verb] attributes。这使用Route("myroute")
来定义路线。
// GET api/issues/severity/5
[Route("severity/{severity}")]
[HttpGet()]
public IEnumerable<Issue> GetBySeverity(int severity)
{
IssueService service = new IssueService();
return service.GetIssuesBySeverity(severity);
}
// GET api/issues/5
[HttpGet("{id}")]
public Issue Get(int id)
{
IssueService service = new IssueService();
return service.GetIssueById(id);
}
以上方法将路由到api/issues/1
和api/issues/severity/1
。如果要使用查询参数而不是url参数进行映射,则以下方法应该起作用:
// GET api/issues/severity?severity=5
[HttpGet("severity")]
public IEnumerable<Issue> GetBySeverity([FromQuery] int severity)
{
IssueService service = new IssueService();
return service.GetIssuesBySeverity(severity);
}
// GET api/issues?id=5
[HttpGet()]
public Issue Get([FromQuery] int id)
{
IssueService service = new IssueService();
return service.GetIssueById(id);
}
以上操作将路由到api/issues?id=1
和api/issues/severity?severity=1