How does ASP.NET Web.api handle two methods with names starting with GET?

后端 未结 3 1447
情话喂你
情话喂你 2021-01-02 11:33

I am looking at the following tutorial from Microsoft. As per this tutorial,

In the first example, \"products\" matches the controller named Produc

3条回答
  •  醉话见心
    2021-01-02 11:47

    There are two possible solutions to this specific problem:

    1. Alter MapHttpRoute calls to require specifying the name of the action. (I'm using Self-hosting syntax):

          config.Routes.MapHttpRoute(
                  "API Route 1",
                  "api/{controller}/{action}");
      
          config.Routes.MapHttpRoute(
                  "API Route 2",
                  "api/{action}",
                  new { controller = "products" });
      

      So your http client would call:

      api/products/GetAllProducts OR api/GetAllProducts api/products/GetSoldProducts OR api/GetSoldProducts

      See: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

    2. Place each method in a separate controller (ProductsController, SoldProductsController). So you would call api/products and api/soldproducts to get your results.


    Related topic... in the situation where you have a multiple Get actions that have a single primitive argument of the same type, ASP.NET Web API will look at the name of the argument to resolve which overloaded action to call.

    For example, if you have two actions:

    GetProductByName(string name) 
    GetProductByCategory(string category) 
    

    your http client can call

    api/products?name=hammer 
    api/products?category=toys
    

    and the routing engine will call the correct action.

提交回复
热议问题