2013-10-31 139 views
0

我有一個ASP.NET MVC應用程序。 我有單一的函數模式,這將被稱爲與HTTP POST和HTTP DELETE。ASP.NET MVC HTTP Post/Delete

雖然調用Post,但絕不會調用Delete。我確認IIS接受HTTP刪除。任何意見?

路線和控制器:

routes.MapHttpRoute(
      name: "RegisterCard", 
      routeTemplate: "{version}/cards/{cardID}", 
      defaults: new { Controller = "MyController", Action = " 

      routes.MapHttpRoute(
      name: "UnregisterCard", 
      routeTemplate: "{version}/cards/{cardID}", 
      defaults: new { Controller = "MyController", Action = "Delete" });     




    [HttpPost] 
    public async Task<HttpResponseMessage> Post(string version, string cardID); 
    { 
    } 

    [HttpDelete] 
    public async Task<HttpResponseMessage> Delete(string version, string cardID); 
    { 
    } 
+0

您正在使用哪個瀏覽器? IE 8和9不會很好地執行AJAX DELETE/PUT。嘗試在請求中添加「X-HTTP-Method-Override:Delete」標題並使用POST。這會觸發行動嗎? – SimonGoldstone

+0

檢查這個答案,並通過您的配置文件 http://stackoverflow.com/questions/10906411/asp-net-web-api-put-delete-verbs-not-allowed-iis-8 –

回答

0

從上面的代碼中,我認爲有圖案{version}/cards/{cardID}任何URL將被「RegisterCard」路線,不管動詞是什麼處理(後/刪除)。對於「刪除」,將選擇「註冊卡」路線,然後當[HttpPost]動作選擇器進場時,它將導致404錯誤。如果您遇到404 「刪除」,你可能會

ONE 添加約束路線

routes.MapHttpRoute(
    name: "RegisterCard", 
    routeTemplate: "{version}/cards/{cardID}", 
    defaults: new { Controller = "MyController", Action = "Post"}, 
    constraints: new { httpMethod = new HttpMethodConstraint(new[] { "post" }) } 
); 

routes.MapHttpRoute(
    name: "UnregisterCard", 
    routeTemplate: "{version}/cards/{cardID}", 
    defaults: new { Controller = "MyController", Action = "Delete" }, 
    constraints: new { httpMethod = new HttpMethodConstraint(new[] { "delete" }) } 
); 

使一個單一的路徑與單一ActionName

routes.MapHttpRoute(
    name: "Card", 
    routeTemplate: "{version}/cards/{cardID}", 
    defaults: new { Controller = "MyController", Action = "HandleCard"} 
); 

[ActionName("HandleCard")] 
[HttpPost] 
public async Task<HttpResponseMessage> Post(string version, string cardID); 
{ 
} 

[ActionName("HandleCard")] 
[HttpDelete] 
public async Task<HttpResponseMessage> Delete(string version, string cardID); 
{ 
} 
在一起,將它們合併

希望這有助於。