2017-06-14 118 views
2

使用的WebAPI angularjs項目,並試圖刪除功能 `的WebAPI 「的請求的資源不支持HTTP方法「刪除」

 [HttpDelete] 
    public String DeleteCountry(string cntryId) 
    { 
     if (cntryId != null) 
     { 
      return repoCountry.DeleteCountry(Convert.ToInt32(cntryId)); 

     } 
     else 
     { 
      return "0"; 

     } 
    } 

js函數是

$http({ 
      method: "delete", 
      url: '/api/Country/DeleteCountry/', 
      dataType: "json", 
      data: { cntryId: cntryId } 
     }).then(function (response) {}); 

在這裏我得到異常

{"Message":"The requested resource does not support http method 'DELETE'."} 

插入,更新和獲取功能工作正常y.給出一個解決方案,爲什麼它發生只刪除

+1

您可以嘗試刪除'data'對象並將cntryId追加到url嗎?我的猜測是ASP.NET路由試圖找到一個沒有參數的HttpDelete動作(因爲URL中沒有)。 – martennis

+1

該參數未標記爲[FromBody],所以如果我記得它的話,它必須放在URL中。 – Gusman

+0

@Gusman這是正確的,默認情況下,綁定從URL查詢參數中查找「簡單」類型。 – phuzi

回答

2

裝飾你的方法與Route屬性(我認爲這給了我更多的控制您的刪除請求發送在網絡API的路由行爲),並通過數據參數,以這種形式構造ARGS:[HttpDelete, Route("{cntryId}")

[HttpDelete, Route("{cntryId}")] 
public String DeleteCountry(string cntryId) 
    { 
    //.... 
    } 

在你的角度控制器,你可以只是這樣做:

$http.delete('/api/Country/' + cntryId).then(function (response) { 
      //if you're waiting some response 
     }) 
+0

如果您不需要更改webapiconfig –

+0

@BRAHIMKamel,則不需要{cntryId},除非在api配置中將默認路由從{id}更改爲{cntryId},否則您需要路由屬性。否則,任何未被命名爲「id」的參數將作爲查詢字符串進行路由。 – ATerry

1

是不是一個webapi問題更是您的查詢格式。 消息說does not support http method 'DELETE'因爲webapi刪除方法期待一個id作爲參數。和路由具有以下格式routeTemplate: "api/{controller}/{id}", 解決您的問題,嘗試使用小提琴手攔截您的請求,並確保爲'/api/Country/DeleteCountry/'+cntryId,

0

選項1:

$http({ 
    method: "delete", 
    url: '/api/Country/Country?cntryId=' + cntryId, 
}).then(function (response) {}); 

選項2:

public String DeleteDeleteCountry([FromBody]string cntryId) 
{ 
    if (cntryId != null) 
    { 
     return repoCountry.DeleteCountry(Convert.ToInt32(cntryId)); 

    } 
    else 
    { 
     return "0"; 

    } 
} 

最佳選項:

API

[Route("{countryId}")] 
public IHttpActionResult Delete(int countryId) 
{ 
    try 
    { 
     repoCountry.DeleteCountry(countryId); 
    } 
    catch (RepoException ex) 
    { 
     if (ex == notfound) 
      this.NotFound(); 
     if (ex == cantdelete) 
      this.Confict(); 
     this.InternalServerError(ex.message); 
    } 
    return this.Ok(); 
} 

的Javascript

$http({ 
    method: "delete", 
    url: '/api/country/' + cntryId, 
}).then(function (response) {}); 
0

假設你沒有改變默認路由。如果您無法爲webAPI中的操作聲明[HttpDelete]屬性,則會發生相同的錯誤。請嘗試以下操作:

[HttpDelete] 
public IHttpActionResult Delete(int id) 
{ 
} 
相關問題