Web API 路由到操作名称 [英] Web API route to action name

查看:26
本文介绍了Web API 路由到操作名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个控制器来返回 JSON 以供 JavaScript 使用,因此我从 ApiController 类继承,但它的行为与我预期的不一样.Apress 书籍 Pro ASP.NET MVC 4 和我发现的大多数在线示例都提供了以下示例:

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" };
}

通过 URL 访问:

http://mysite/services/methodfruit

但这永远行不通 - 找不到资源.我可以开始工作的唯一方法是让控制器为每个 HTTP 动词包含一个不同的方法,然后:

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

调用 GET 方法.

我查看了 Apress 网站,但他们似乎没有任何论坛,当前的源代码在 VS 2012 中,我没有使用.我检查了源文件,他们似乎认为前一种方法应该有效.是否不再支持前一种方法?

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?

推荐答案

是的...通常您必须遵循 ASP.NET WEB API 期望的默认命名约定.

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

查看此官方文档:

ASP.NET 中的路由网页 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.

按动作名称路由

使用默认路由模板,Web API 使用 HTTP 方法选择操作.但是,您也可以创建一条路线,其中动作名称包含在 URI 中:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆