Model null when use Route attribute

[亡魂溺海] 提交于 2021-02-10 20:18:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!