Detect if action is a POST or GET method

Solution 1:

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.

Solution 2:

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
 }

Solution 3:

To detect this in ASP.NET Core:

if (Request.Method == "POST") {
    // The action is a POST
}

Solution 4:

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

Solution 5:

If you're like me and prefer not to use a string literal (.net core 2.2 middleware using DI):

public async Task InvokeAsync(HttpContext context)
{
    if (context.Request.Method.Equals(HttpMethods.Get, StringComparison.OrdinalIgnoreCase))
    {
        …
    }
}