本文介绍了ASP.NET MVC HTTP发布/删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC应用程序.我有一个单一的功能模式,可以通过HTTP POST和HTTP DELETE调用.

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

尽管调用了Post,但从未调用过Delete.我确认IIS接受HTTP删除.有任何评论吗?

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

路由和控制器:

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

推荐答案

从上面的代码中,我认为任何模式为{version}/cards/{cardID}的url都将由"RegisterCard"路由处理,无论动词是什么(发布/删除) .对于删除",将选择"RegisterCard"路由,然后当[HttpPost]动作选择器起作用时,将导致404错误.如果您遇到删除"的404错误,则可能

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

一个向路线添加约束

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 进行一条路由,将它们与单个ActionName

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

希望这会有所帮助.

这篇关于ASP.NET MVC HTTP发布/删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 10:49