Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...