andrewb
andrewb

Reputation: 3095

Understanding how WebApi routes requests

I am new to WebApi and I followed this tutorial https://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

Everything works as expected - I have 2 endpoints

api/products
api/products/id

What I am trying to understand is how they relate to the methods defined in my controller.

For example, when I hit the api/products endpoint the action which runs is called GetAllProducts

And when I hit the api/products/id endpoint the action which runs is called GetProduct

So how does the WebApi engine know to direct the user to those endpoints?

My WebapiConfig.cs is

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

Controller:

Product[] products = new Product[]
{
    new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
    new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
    new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};

public IEnumerable<Product> GetAllProducts()
{
    return products;
}

public IHttpActionResult GetProduct(int id)
{
    var product = products.FirstOrDefault((p) => p.Id == id);
    if (product == null)
    {
        return NotFound();
    }
    return Ok(product);
}

Upvotes: 0

Views: 118

Answers (2)

jbsmith
jbsmith

Reputation: 1666

I think you'll find this link very illuminating:

https://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection

To select an action, it looks at the following:

The HTTP method of the request.

The "{action}" placeholder in the route template, if present.

The parameters of the actions on the controller.

In your case, it's the last option that dictates which method is invoked -- as Mike said in his comment, it's based on the signatures.

Upvotes: 2

Amit
Amit

Reputation: 3478

Everything is controlled as how the routing is defined... As you can see that the ID param is optional.. so whenever you hit request api/products - your request will be matched against the routing table and it sees that ID is not passed which is ok because it is defined as optional... so your method GetAllProducts is invoked....

whereas if you pass the ID in url... you are explicitely setting up the optional param which is again matching with your routing... and thus you get product detail of specified id.

Upvotes: 0

Related Questions