Crystal Crystal - 15 days ago 4x
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

if you don't have any query parameters.

For example, I have this model:

public class GetBooksRequest
public int? BookLimit { get; set; }

Used in the following action

public IHttpActionResult Get([FromUri]GetBooksRequest request) {
// request is null

Is parameter value supposed to be
if I hit

It hits my endpoint, but parameter is
. If I do
, then parameter is not
and the
property is set to
as expected.

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


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: