Model null when use Route attribute

2017-07-21 c# asp.net-mvc asp.net-web-api routing

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?

Answers

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.

If you want to init model using Route attributes try

Route("api/users/{*pathvalue}")]

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.

Related