Search code examples
c#asp.net-web-apiasp.net-web-api-routing

WebApi attribute routing - Bind route parameter to an object for GETs


Currently for every GET I have to manually create a query object from the route parameters.

Is it possible to bind directly to a query object instead?

So, instead of :

[Route("{id:int}")]
public Book Get(int id) {

    var query = new GetBookByIdQuery {
        Id = id
    };

    // execute query and return result
}

I could do this:

[Route("{id:int}")]
public Book Get(GetBookByIdQuery query) {
    // execute query and return result
}

Where GetBookByIdQuery looks like:

public class GetBookByIdQuery {
    public int Id { get; set;}
}

Solution

  • to read a complex type from the URI, [FromUri] can be used

        [Route("{id:int}")]
        public Book Get([FromUri] GetBookByIdQuery query) {
    
            // execute query and return result
        }
    

    if you request api/values/2 then id property of query object will be 2;