c# - WebAPI ActionName 路由半工作

标签 c# angularjs asp.net-mvc-4 asp.net-web-api

我一直在构建一个 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 )

  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/

相关文章:

javascript - 数组中对象的 Angular 复选框

asp.net-mvc - 处理 OAuth 2.0 身份验证 - 在 ASP.NET MVC 应用程序中获取 token 重定向 token 响应

jquery - 使用 Jquery Ajax 将模型从 View 传递到 Controller

c# - 将对象添加到泛型 List<T> 的开头

html - 如何对齐 Angular-Material 工具栏中的文本输入?

javascript - 将计算值包含在 Angular 滤波器结果中

c# - MVC Controller 无法执行异步方法

c# - 是否需要显式事务回滚?

c# - 实例化和接口(interface)

c# - 如果字符串大于 255 个字符,则删除字符