gpt4 book ai didi

c# - WebAPI ActionName 路由半工作

转载 作者:行者123 更新时间:2023-11-30 21:46:02 26 4
gpt4 key购买 nike

我一直在构建一个 WebAPI,尝试使用 ActionName 路由到正确的方法。它适用于我尝试调用的一种方法,但另一种方法出现 404 错误。

我的 WebAPI 配置文件:

public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

// Web API routes
config.MapHttpAttributeRoutes();

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

我的 WebAPI Controller 方法的格式如下:

第一个是工作的:

[ActionName("postdb")]
public IEnumerable<string[]> postDB(string id)
{ ...

第二个没有:

[ActionName("getquery")]
public IEnumerable<string[]> getQuery(string tables)
{ ...

我从 angular 中以相同的方式调用它们(Temp 是一个作为参数传递的字符串):

$http.post('api/Test/postdb/' + temp).then(function (response) { ...

$http.get('api/Test/getquery/' + temp).then(function (response) { ...

我试过更改两个 Action 的名称,第一个无论名称如何都有效,第二个无论名称如何都无效。我也尝试过重新排序它们,在 GET 和 POST 之间切换,以及更改参数。

有什么建议吗?

最佳答案

不确定为什么要使用 ActionName 来设置路由?

您可能应该查看 Route 属性。例如。

[HttpPost]
[Route("postdb")]
// Action doesn't have to be called 'postdb'
public IEnumerable<string[]> postDB(string id)

ActionName 通常用于不同的目的 ( Purpose of ActionName )

尽管如此,我认为您的示例中发生了一些奇怪的事情 - 我认为设置 ActionName 不应该影响那里的路由。要进行调试,我建议设置失败请求跟踪以查看请求在哪个点未能到达操作。

这些是 WebAPI 中 Action 选择的基本规则 (http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection)

  1. You can specify the HTTP method with an attribute: AcceptVerbs, HttpDelete, HttpGet, HttpHead, HttpOptions, HttpPatch, HttpPost, or HttpPut.

  2. Otherwise, if the name of the controller method starts with "Get", "Post", "Put", "Delete", "Head", "Options", or "Patch", then by convention the action supports that HTTP method.

  3. If none of the above, the method supports POST.

因此,在您的示例中,postdb 方法可能 映射到 POST 方法。但可能是,因为它是小写的 ASP.NET 不喜欢那样并应用规则 3 - 尝试使用 ActionName("PostDB")[ActionName( "GetQuery")] 如果您真的想使用 ActionName(无论出于何种原因)而不是 Route

关于c# - WebAPI ActionName 路由半工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39563099/

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