asp.net core razor 页面支持删除和放置请求

问题描述:

最近,我阅读了有关在 asp.net core razor 页面中处理请求的内容,它说它支持使用约定的 head 请求:

Recently, I read about request handling in asp.net core razor pages and it says that it supports head requests using the convention:

public void OnHead()
{
}

它工作得很好.然后我也尝试使用相同的约定删除.

It worked perfectly. And then I also tried delete using the same convention.

public void OnDelete()
{
}

但是当我使用邮递员发送删除请求时,它返回一个错误的请求 (500).我不确定是否需要提供额外的配置来使用删除请求.任何人都可以帮助我.

But when I send a delete request using postman, it returns a bad request (500). I'm not sure if i need to provide additional configurations to use delete requests. Any one could help me pls.

没有OnDelete/OnPut.这是因为 Razor 页面直接面向 Web 视图,即在浏览器选项卡/窗口中显示的页面.浏览器中没有发送 DELETE/PUT 请求的本机方式,因此没有理由支持它们.相反,此类任务是通过 HTML 表单元素处理的,该元素将通过 POST 发送.因此,您将使用 OnPost() 来处理它.

There is no OnDelete/OnPut. This is because Razor Pages are directly geared towards web views, i.e. pages displaying in a browser tab/window. There is no native way in a browser to send DELETE/PUT requests, so there's no reason to support them. Instead, such tasks are handled via an HTML form element, which would send via POST. As such, you would use OnPost() to handle it.

文档建议使用自己的 OnGetOnPost 方法创建一个用于删除的新 Razor 页面,专门用于处理删除.或者,您可以简单地以 OnPost[Something] 的形式向现有 Razor 页面添加一个额外的处理程序.对于删除,可能是 OnPostDelete,而对于更新,您可能有 OnPostUpdate.名称无关紧要,只是您需要将其作为 handler 传递,例如:

The docs recommend creating a new Razor Page for delete, with its own OnGet and OnPost methods, specifically geared to handling deletes. Alternatively, you may simply add an additional handler to an existing Razor Page in the form of OnPost[Something]. For a delete, that would likely be OnPostDelete, while for an update, you'd likely have OnPostUpdate. The name doesn't matter, except that you will need to pass it as a handler such as:

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

如果您需要通过瘦客户端(HttpClient、AJAX、Postman 等)进行交互,那么您应该完全避免使用 Razor Pages 并坚持使用完全支持所有 HTTP 动词的传统控制器.

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.