以动作名称的Web API路线 [英] Web API route to action name
问题描述
我需要一个控制器返回JSON由JavaScript的消耗,所以我从 ApiController
类继承,但正如我预期它不表现。在A preSS书临ASP.NET MVC 4,大部分的在线例子,我发现给像例子:
公共类ServicesController:ApiController
{
公共字符串[] MethodFruit()
{
返回新的字符串[] {苹果,橙色,香蕉};
}
通过URL访问:
的http:// mysite的/服务/ methodfruit
但从未工程 - 资源未找到。我可以得到工作的唯一方法是让控制器包含一个不同的方法,为每个HTTP动词,然后是:
的http:// mysite的/ API /服务
它调用GET方法。
我查了A preSS的网站,但他们似乎并不有任何论坛和电流源$ C $ c是在VS 2012这我不使用。我检查了源文件,他们似乎认为前者的做法应该工作。是前者的做法不再支持?
是的...一般你必须遵循的ASP.NET Web API的预期默认的命名约定。
检查这个官方文档:
<一个href=\"http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api\">Routing在的ASP.NET Web API
如果你不想遵循约定,你可以尝试一下的按动作名称路由的在上面链接的文档中描述部分。
路由通过操作名称
使用默认的路由模板,网页API使用HTTP方法
选择操作。不过,你也可以创建一个路由,其中
动作名称被包括在URI:
块引用>routes.MapHttpRoute(
名称:ActionApi
routeTemplate:API / {控制器} / {行动} / {ID}
默认:新{ID = RouteParameter.Optional});在你的情况,你必须做到这一点:
[HTTPGET]
公共字符串[] MethodFruit()
{
返回新的字符串[] {苹果,橙色,香蕉};
}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?
解决方案Yep... generally you have to follow the default naming convention expected by ASP.NET WEB API.
Check this official doc:
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" }; }
这篇关于以动作名称的Web API路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!