2017-01-10 174 views
1

$ .http reqeust和Web API都在本地主機,但不同的應用「的請求的資源不支持HTTP方法 'POST' - 405響應

角JS(在其他asp.net應用程序

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

網頁API(在單獨的應用程序)

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

錯誤respon SE:

{ 「消息」: 「所請求的資源不支持HTTP方法 'POST'。」}

網頁API 2 - 已標有[HTTPPOST]即使不需要。

我reqeust和響應報文如下:

**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錯誤。

+0

請通過服務器端代碼以及 –

+0

其已發佈。 – dsi

回答

1

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){ 
     ... 
} 
+0

非常感謝。有用。 :)謝謝你的解釋。 – dsi

+0

不客氣。而解釋是重要的:)很多人只是發佈代碼 – Darren

+0

是的。對。謝謝。 – dsi

相關問題