Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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). I'm not sure if i need to provide additional configurations to use delete requests. Any one could help me pls.

like image 668
Harun Diluka Heshan Avatar asked Dec 04 '22 18:12

Harun Diluka Heshan


2 Answers

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).

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

Further, the Async suffix is optional:

The Async naming suffix is optional but is often used by convention for asynchronous functions.

like image 148
haldo Avatar answered Dec 06 '22 07:12

haldo


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.

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">

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.

like image 42
Chris Pratt Avatar answered Dec 06 '22 06:12

Chris Pratt