gpt4 book ai didi

c# - Action 名称的 Web API 路由

转载 作者:可可西里 更新时间:2023-11-01 03:12:53 25 4
gpt4 key购买 nike

我需要一个 Controller 来返回 JSON 以供 JavaScript 使用,因此我继承了 ApiController 类,但它的行为并不像我预期的那样。 Apress 书籍 Pro ASP.NET MVC 4 和我找到的大多数在线示例都提供了如下示例:

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

通过 URL 访问:

http://mysite/services/methodfruit

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

http://mysite/api/services

调用 GET 方法。

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

最佳答案

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

查看官方文档:

Routing in ASP.NET Web API

如果您不想遵循约定,可以尝试上述链接文档中描述的按操作名称路由部分。

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

在您的情况下,您必须这样做:

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

关于c# - Action 名称的 Web API 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18661946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com