The HttpMethod
property on the HttpRequest
object will get it for you. You can just use:
if (HttpContext.Current.Request.HttpMethod == "POST")
{
// The action is a POST.
}
Or you can get the Request
object straight off of the current controller. It's just a property.
Its better to compare it with HttpMethod
Property rather than a string.
HttpMethod is available in following namespace:
using System.Net.Http;
if (HttpContext.Request.HttpMethod == HttpMethod.Post.Method)
{
// The action is a post
}
To detect this in ASP.NET Core:
if (Request.Method == "POST") {
// The action is a POST
}
Starting From .Net Core 3, you can use HttpMethods.Is{Verb}
, like this:
using Microsoft.AspNetCore.Http
HttpMethods.IsPost(context.Request.Method);
HttpMethods.IsPut(context.Request.Method);
HttpMethods.IsDelete(context.Request.Method);
HttpMethods.IsPatch(context.Request.Method);
HttpMethods.IsGet(context.Request.Method);
You can even go further and create your custom extension to check whether it is a read operation or a write operation, something like this:
public static bool IsWriteOperation(this HttpRequest request) =>
HttpMethods.IsPost(request?.Method) ||
HttpMethods.IsPut(request?.Method) ||
HttpMethods.IsPatch(request?.Method) ||
HttpMethods.IsDelete(request?.Method);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With