【问题标题】:WebAPI ActionName routing half workingWebAPI ActionName 路由一半工作
【发布时间】:2017-01-26 13:10:13
【问题描述】:

我一直在构建 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 控制器方法的格式如下:

第一个是工作的:

[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 之间更改,以及更改参数。

有什么建议吗?

【问题讨论】:

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


    【解决方案1】:

    不确定为什么要使用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. 您可以使用属性指定 HTTP 方法:AcceptVerbs、HttpDelete、HttpGet、HttpHead、HttpOptions、HttpPatch、HttpPost 或 HttpPut。

    2. 否则,如果控制器方法的名称以“Get”、“Post”、“Put”、“Delete”、“Head”、“Options”或“Patch”开头,那么按照惯例,该操作支持HTTP 方法。

    3. 如果以上都不是,该方法支持POST。

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

    【讨论】:

    • 感谢您的建议。我会努力把它改成那个!
    【解决方案2】:

    第二个动作中参数tables的名称

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

    与路由中参数id的名称不匹配:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-12
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      • 2019-01-09
      • 1970-01-01
      • 2010-10-09
      • 1970-01-01
      相关资源
      最近更新 更多