简体   繁体   English

asp.net core razor pages 支持delete和put请求

[英]asp.net core razor pages support for delete and put requests

Recently, I read about request handling in asp.net core razor pages and it says that it supports head requests using the convention:最近,我在 asp.net 核心 razor 页面中阅读了有关请求处理的内容,它说它支持使用约定的head请求:

public void OnHead()
{
}

It worked perfectly.它工作得很好。 And then I also tried delete using the same convention.然后我也尝试使用相同的约定删除。

public void OnDelete()
{
}

But when I send a delete request using postman, it returns a bad request (500).但是当我使用 postman 发送删除请求时,它返回一个错误的请求 (500)。 I'm not sure if i need to provide additional configurations to use delete requests.我不确定我是否需要提供额外的配置来使用删除请求。 Any one could help me pls.任何人都可以帮助我。

Assuming you have a markup like this:假设您有这样的标记:

<button type="submit" asp-page-handler="delete" 
        asp-route-id="@contact.Id">delete</button>

The correct method for delete would be OnPostDelete (or OnPostDeleteAsync ).正确的删除方法是OnPostDelete (或OnPostDeleteAsync )。

So, could update to:所以,可以更新为:

public void OnPostDelete(int id)
{
}

The docs state: 文档状态:

By convention, the name of the handler method is selected based on the value of the handler parameter according to the scheme OnPost[handler]Async按照惯例,处理程序方法的名称是根据方案OnPost[handler]Async根据处理程序参数的值选择的

Further, the Async suffix is optional:此外, Async后缀是可选的:

The Async naming suffix is optional but is often used by convention for asynchronous functions. Async命名后缀是可选的,但通常按惯例用于异步函数。

There is no OnDelete / OnPut .没有OnDelete / OnPut This is because Razor Pages are directly geared towards web views, ie pages displaying in a browser tab/window.这是因为 Razor 页面直接面向 Web 视图,即在浏览器选项卡/窗口中显示的页面。 There is no native way in a browser to send DELETE/PUT requests, so there's no reason to support them.浏览器中没有发送 DELETE/PUT 请求的本机方式,因此没有理由支持它们。 Instead, such tasks are handled via an HTML form element, which would send via POST.相反,此类任务是通过 HTML 表单元素处理的,该元素将通过 POST 发送。 As such, you would use OnPost() to handle it.因此,您将使用OnPost()来处理它。

The docs recommend creating a new Razor Page for delete, with its own OnGet and OnPost methods, specifically geared to handling deletes.文档建议使用自己的OnGetOnPost方法创建一个新的用于删除的 Razor 页面,专门用于处理删除。 Alternatively, you may simply add an additional handler to an existing Razor Page in the form of OnPost[Something] .或者,您可以简单地以OnPost[Something]的形式向现有 Razor 页面添加一个额外的处理程序。 For a delete, that would likely be OnPostDelete , while for an update, you'd likely have OnPostUpdate .对于删除,可能是OnPostDelete ,而对于更新,您可能有OnPostUpdate The name doesn't matter, except that you will need to pass it as a handler such as:名称无关紧要,只是您需要将其作为handler传递,例如:

<form asp-page="Foo" asp-handler="Delete">

If you need to interact via a thin client ( HttpClient , AJAX, Postman, etc.), then you should avoid Razor Pages altogether and stick with traditional controllers, which fully supports all HTTP verbs.如果您需要通过瘦客户端( HttpClient 、AJAX、Postman 等)进行交互,那么您应该完全避免使用 Razor Pages 并坚持使用完全支持所有 HTTP 动词的传统控制器。

This is an update for 2023.这是 2023 年的更新。

You can easily utilize the DELETE verb of an Ajax request:您可以轻松地使用 Ajax 请求的 DELETE 动词:

public async Task<IActionResult> OnDeleteAsync(int id)
{
    await _myService.DeleteUser(id);

    return new OkResult();
}

With jQuery it looks something like this:对于 jQuery,它看起来像这样:

<script>

$(".deletebtn").on("click", function (e) { 
    deleteUser($(this).data("id"));
});

const deleteUser = function (userId) {
    $.ajax({
        method: 'DELETE', // specify HTTP verb.
        url: '/account/users', // specify right path to your controller/razor page
        headers:
        {
            "RequestVerificationToken": "<get your token here>"
        },
        data: { id: userId },
        success: function () {
            window.location.href = "/account/users"; // reload page
        },
        error: function (response) {
            alert(response);
        }
    });
};

</script>
<button class="deletebtn" data-id="123">Delete</button>
<button class="deletebtn" data-id="456">Delete</button>
<button class="deletebtn" data-id="1111">Delete</button>

Similarly the HTTP verbs GET, POST, PUT can also be utilized:类似地,也可以使用 HTTP 动词 GET、POST、PUT:

OnGet(), OnPost(), OnPut()

and their async equivalents和他们的异步等价物

OnGetAsync(), OnPostAsync(), OnPutAsync()

Usage eg:用法例如:

OnGetUsersAsync() // GET a list of Users async. 
OnPostUserAsync() // POST (add) a User async. 
OnPutUpdateMyUserAsync() // PUT (update) a user async
OnDeleteCoffeCup(id)  /// DELETE method sync.

In addition you can add your own experimental HTTP verbs.此外,您还可以添加自己的实验性 HTTP 动词。 See eg here https://khalidabuhakmeh.com/adding-experimental-http-methods-to-as.net-core参见此处https://khalidabuhakmeh.com/adding-experimental-http-methods-to-as.net-core

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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