我一直在构建一个 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) { ...
我尝试更改这两个操作的名称,第一个操作无论名称如何都有效,第二个操作无论名称如何都不起作用。我还尝试过对它们重新排序,在 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 中操作选择的基本规则 ( http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection )
You can specify the HTTP method with an attribute: AcceptVerbs, HttpDelete, HttpGet, HttpHead, HttpOptions, HttpPatch, HttpPost, or HttpPut.
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.
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/