"请求的资源不支持http方法' POST' - 405回复

时间:2017-01-10 13:13:26

标签: javascript asp.net angularjs ajax asp.net-web-api2

$ .http reqeust和web api都在localhost上但不同的应用程序。

angular js(在其他asp.net应用程序中

 return $http({
   method: "POST",                       
   url: config.APIURL + 'Parts',
   data: {'final':'final'},
   headers: { 'Content-Type': 'application/json' }
 });

web api(在单独的应用程序中)

[HttpPost]
public Part Post(string final)
{
               ...
}

错误回复:

  

{" Message":"请求的资源不支持http方法   ' POST'"}

web api 2 - 已标记为[HTTPPOST],即使不需要。

我的需求和响应数据包如下:

**General**
    Request URL:http://localhost/SigmaNest.WebAPI/api/Parts
    Request Method:POST
    Status Code:405 Method Not Allowed
    Remote Address:[::1]:80
    **Response Headers**
    view source
    Allow:GET
    Cache-Control:no-cache
    Content-Length:73
    Content-Type:application/json; charset=utf-8
    Date:Tue, 10 Jan 2017 13:05:59 GMT
    Expires:-1
    Pragma:no-cache
    Server:Microsoft-IIS/10.0
    X-AspNet-Version:4.0.30319
    X-Powered-By:ASP.NET
    **Request Headers**
    view source
    Accept:application/json, text/plain, */*
    Accept-Encoding:gzip, deflate, br
    Accept-Language:en-US,en;q=0.8
    Connection:keep-alive
    Content-Length:17
    Content-Type:application/json;charset=UTF-8
    Host:localhost
    Origin:http://localhost
    Referer:http://localhost/SigmaNest.Web/app/views/index.html
    User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
    **Request Payload**
    view source
    {final: "final"}
    final
    :
    "final"

任何人都可以帮我解决这个405错误。

1 个答案:

答案 0 :(得分:2)

ASP.Net正在努力将您的Ajax帖子与适当的控制器操作相匹配,因为它没有与您尝试调用的内容相匹配。

在这种情况下,您尝试传递对象{'final':'final'}但正在接受字符串。 Post(string final)和ASP.Net无法将此与已启用POST的任何特定操作相匹配。

您可以对您的javascript对象进行字符串化

return $http({
   method: "POST",                       
   url: config.APIURL + 'Parts',
   data: JSON.stringify({'final':'final'}), // Strinify your object
   headers: { 'Content-Type': 'application/json' }
 });

或者,更改服务器端方法以接收与您正在提供的对象匹配的类。例如:

// DTO MyObject - .Net will ModelBind your javascript object to this when you post
public class MyObject{
  public string final {get;set;}
}
// change string here to your DTO MyObject
public Part Post(MyObject final){
      ...
}