Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if action is a POST or GET method

Tags:

c#

asp.net-mvc

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