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
354 views
in Technique[技术] by (71.8m points)

c# - Web API route to action name

I need a controller to return JSON to be consumed by JavaScript so I inherited from the ApiController class but it isn't behaving as I expected. The Apress book Pro ASP.NET MVC 4 and most of the online examples I've found give examples like:

public class ServicesController : ApiController
{
    public string[] MethodFruit()
    {
        return new string[] { "Apple", "Orange", "Banana" };
}

accessed via the URL:

http://mysite/services/methodfruit

But that never works - the resource isn't found. The only approach I can get working is to have the controller contain a different method for each HTTP verb, then:

http://mysite/api/services

Which calls the GET method.

I checked the Apress website but they don't seem to have any forums and the current source code is in VS 2012 which I'm not using. I examined the source files and they seem to think the former approach should work. Is the former approach no longer supported?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Yep... generally you have to follow the default naming convention expected by ASP.NET WEB API.

Check this official doc:

Routing in ASP.NET Web API

If you do not want to follow the convention, you can try the Routing by Action Name section described in the above linked doc.

Routing by Action Name

With the default routing template, Web API uses the HTTP method to select the action. However, you can also create a route where the action name is included in the URI:

routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional } );

In your case, you'd have to do this:

[HttpGet]
public string[] MethodFruit()
{
    return new string[] { "Apple", "Orange", "Banana" };
}

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

...