Detect if action is a POST or GET method

前端 未结 4 1251
孤街浪徒
孤街浪徒 2020-12-14 00:01

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

相关标签:
4条回答
  • 2020-12-14 00:32

    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.

    0 讨论(0)
  • 2020-12-14 00:44

    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
     }
    
    0 讨论(0)
  • 2020-12-14 00:45

    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))
        {
            …
        }
    }
    
    0 讨论(0)
  • 2020-12-14 00:54

    To detect this in ASP.NET Core:

    if (Request.Method == "POST") {
        // The action is a POST
    }
    
    0 讨论(0)
提交回复
热议问题