问题
In my WebAPI
I have model
public class ListRequest
{
public int Skip { get; set; } = 0;
public int Take { get; set; } = 30;
}
My action is
[HttpGet]
[Route("api/users")]
public IHttpActionResult Get([FromUri] ListRequest request) {
...
}
I need to have possibility to not pass any query parameters, then default values should be used. But, when I go to http://localhost:44514/api/users
the request
is null. If I remove [Route("api/users")]
then request
is not null and has default values for parameters.
How can I reach that behavior with Route attribute?
回答1:
If you want to init model using Route attributes try
Route("api/users/{*pathvalue}")]
回答2:
Create your method on post request basis. Get type always receive null value.
[HttpGet]
[Route("api/users")]
public IHttpActionResult Get([FromUri] ListRequest request) {
}
Change to
[HttpPost]
[Route("api/users")]
public IHttpActionResult Get([FromUri] ListRequest request) {
...
}
Because Model (Class) type parameter does not support get type request.
Hope it will help.
回答3:
Use data annotation. For more information visit Default value in mvc model using data annotation
Change
public class ListRequest
{
public int Skip { get; set; } = 0;
public int Take { get; set; } = 30;
}
To
public class ListRequest
{
[DefaultValue(0)]
public int Skip { get; set; }
[DefaultValue(30)]
public int Take { get; set; }
}
It works without removing [Route("api/users")] and request will not be null.
来源:https://stackoverflow.com/questions/45235203/model-null-when-use-route-attribute