简体   繁体   中英

ASP.NET MVC HTTP Post/Delete

I have a ASP.NET MVC app. I have single function pattern which will be called both with HTTP POST and HTTP DELETE.

Although Post is called, Delete is never called. I confirmed that the IIS accepts HTTP Delete. Any comments?

Route and Controllers:

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);
    {
    }

From the code above, i think any url with pattern {version}/cards/{cardID} will be handled by "RegisterCard" route no matter what the verb is(Post/Delete). For "Delete", "RegisterCard" route will be chosen, then when [HttpPost] action selector comes into play, it will result in a 404 error. If you are experiencing 404 for "Delete", you might

ONE Add constraint to routes

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" }) }
); 

OR Make a single route merging them together with a single 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);
{
}

hope this helps.

I'm not sure that HTTP supports delete. Regardless, Just use post for your delete action. As long as you're not useing GET for a DELETE action, you're good. Here's some reference...

http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/examining-the-details-and-delete-methods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM