首页 / 问答 / [.NET/.NET Core].NET Core 应用程序中如何判断当前请求HttpContext.Request是GET还是POST?

[.NET/.NET Core].NET Core 应用程序中如何判断当前请求HttpContext.Request是GET还是POST?

.NET C# HTTP .NET Core ASP.NET Core 3.08K 次浏览
0

在ASP.NET或者ASP.NET Core或者ASP.NET Core Web API的应用程序中,如何判断当前请求(HttpContext.Request)是GET还是POST请求呢?

回复 [×]
提交评论
请输入评论内容

4 个回答

  • 0

    在ASP.NET Core 2.1中,可以使用Request.HttpContext.Request.Method来获取当前请求的谓词,如:

    var verb = Request.HttpContext.Request.Method;
    

    在ASP.NET Core 3.1中,可以使用HttpContext.Request.Method来获取当前请求的谓词,如:

    ```csharp
    var verb = HttpContext.Request.Method;
    

    ```

    Rector的个人主页

    Rector

    2021-04-13 回答

    • 0

      在传统的ASP.NET或者ASP.NET MVC的应用程序中,你可以使用HttpContext.Current.Request.HttpMethod属性来获取当前请求的谓词,如下:

      var verb = HttpContext.Current.Request.HttpMethod;
      
      Rector的个人主页

      Rector

      2021-04-13 回答

      • 0

        在ASP.NET Core 3.1中,你还可以通过注入IHttpContextAccessor的服务来获取当前请求的谓词,如下:

        private readonly IHttpContextAccessor _httpContextAccessor;
        
        public MyPage(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
        

        获取谓词方式:

        var verb = _httpContextAccessor.HttpContext.Request.Method;
        
        Rector的个人主页

        Rector

        2021-04-13 回答

        • 0

          在.NET Core 3中,还可以使用HttpMethods.Is{Verb}方法来检测/判断当前请求的谓词,如:

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

          HttpMethodsIs{Verb}方法有:

          Rector的个人主页

          Rector

          2021-04-13 回答

          我来回答