考虑控制器:
public class EmployeeController : ApiController
{
// https://localhost:44344/api/employee/:profession
[HttpGet]
[Route("api/employee/{profession}")]
public HttpResponseMessage Get(String profession)
{
try
{
var someBigList = ...
/// ... do some stuff
return Request.CreateResponse(HttpStatusCode.OK, someBigList );
}
catch (Exception e)
{
// error
}
}
}
控制器接受以下形式的请求:
https://localhost:44344/api/employee/:profession
但是当我尝试
https://localhost:44344/api/employee
没有。
我们如何解决GET请求以接受两者?
You can mark optional parameters in the route with
?
so this would be[Route("api/employee/{profession?}")]
Or if you want it to have a default value in case no value is given then use
[Route("api/employee/{profession=value}")]
See more from the documentation
If it's not a required parameter then it should be taken from query, not route. So you should use
[FromQuery] string profession
and the usage is as following: https://localhost:44344/api/employee?profession=developer