Crystal Crystal - 2 months ago 10
C# Question

get request in web api null?

I just started using web api and I was wondering if the parameter value is supposed to be

null
if you don't have any query parameters.

For example, I have this model:

[DataContract]
public class GetBooksRequest
{
public int? BookLimit { get; set; }
}


Used in the following action

[HttpGet]
[Route("api/books")]
public IHttpActionResult Get([FromUri]GetBooksRequest request) {
// request is null
}


Is parameter value supposed to be
null
if I hit
api/books
?.

It hits my endpoint, but parameter is
null
. If I do
api/books?booklimit=1
, then parameter is not
null
and the
BookLimit
property is set to
1
as expected.

I just wasn't sure if that's the way web api works.

Answer

Yes that is how it works. The framework inspects the request and will build up the model from the URI (because it was told to check by [FromUri] attribute).

If it cannot build the model with the provided information the model/parameter will be set to its default value, in this case null. That is by design.

Source: Parameter Binding in ASP.NET Web API

Using [FromUri]

To force Web API to read a complex type from the URI, add the [FromUri] attribute to the parameter. The following example defines a GeoPoint type, along with a controller method that gets the GeoPoint from the URI.

public class GeoPoint
{
    public double Latitude { get; set; } 
    public double Longitude { get; set; }
}

public ValuesController : ApiController
{
    public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }
}

The client can put the Latitude and Longitude values in the query string and Web API will use them to construct a GeoPoint. For example:

http://localhost/api/values/?Latitude=47.678558&Longitude=-122.130989