In MVC 3, is it possible to determine if an action is a result of a POST or GET method? I know you can decorate the actions with [HttpPost] and [HttpGet] to fire a specific
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
}
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))
{
…
}
}
To detect this in ASP.NET Core:
if (Request.Method == "POST") {
// The action is a POST
}