Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

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

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

In the first example, "products" matches the controller named ProductsController. The request is a GET request, so the framework looks for a method on ProductsController whose name starts with "Get...". Furthermore, the URI does not contain the optional {id} segment, so the framework looks for a method with no parameters. The ProductsController::GetAllProducts method meets all of these requirements.

What happens if there are two methods like GetAllProducts() and GetSoldProducts()? Both have no parameters.

Your First Web API Tutorial

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...