【问题标题】:ASP. NET Web Api 2 issue - The requested resource does not support HTTP method 'GET'ASP。 NET Web Api 2 问题 - 请求的资源不支持 HTTP 方法“GET”
【发布时间】:2017-07-03 05:03:46
【问题描述】:

我不确定为什么在对我的 api 的以下 GET 调用(使用 PostMan)时收到“404 Not Found”

http://localhost:53840/api/v1/MessageLog/SomeStuff/3

Controller中的方法如下

    [System.Web.Http.HttpGet]
    public string SomeStuff(int s)
    {            
        return "Received input !";            
    }  

WebApiConfig类中的Register方法唯一路由如下:

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

但是当我将代码更改为

    [System.Web.Http.HttpGet]
    public string SomeStuff()
    {            
        return "Received input !";            
    }  

调用http://localhost:53840/api/v1/LogMessage/SomeStuff 有效,POSTMAN 显示“已收到输入!”响应正文中的字符串。

是否有特定的调用约定来传递 int/string 等(我尝试使用 [FromUri] 没有多大成功)?我在控件中有另一个 POST 方法,它需要一个 JObject 并且似乎工作得很好。

【问题讨论】:

    标签: asp.net-web-api2 asp.net-web-api-routing


    【解决方案1】:

    应该是这样的:

    [System.Web.Http.HttpGet]
    public string SomeStuff(int id)
    {            
        return "Received input !";            
    }
    

    Web API 按名称匹配参数。在您的路由模板中,它被定义为{id},因此操作参数名称必须与之匹配。

    第二个起作用的原因是因为 id 是可选的,并且操作与模板匹配。

    【讨论】:

      猜你喜欢
      • 2013-03-05
      • 2020-09-19
      • 2012-06-15
      • 2016-11-26
      • 2013-07-31
      • 1970-01-01
      • 2012-09-27
      • 2014-01-28
      • 2015-10-08
      相关资源
      最近更新 更多