当前Http上下文的Http动词

本文关键字:Http 动词 上下文 当前 | 更新日期: 2023-09-27 18:04:13

如何找到用于访问应用程序的http谓词(POST、GET、DELETE、PUT) ?我正在寻找httpcontext。目前,但似乎没有任何属性,给我的信息。由于

当前Http上下文的Http动词

使用HttpContext.Current.Request.HttpMethod

见:http://msdn.microsoft.com/en-us/library/system.web.httprequest.httpmethod.aspx

您可以使用

获取(或设置)当前上下文的HTTP动词:
Request.HttpContext.Request.Method
HttpContext.Current.Request.HttpMethod
if (HttpContext.Request.HttpMethod == HttpMethod.Post.Method) 
{
        // The action is a post 
}
    
if (HttpContext.Request.HttpMethod == HttpMethod.put.Method)
{
        // The action is a put 
}
if (HttpContext.Request.HttpMethod == HttpMethod.DELETE.Method)
{
        // The action is a DELETE
}
if (HttpContext.Request.HttpMethod == HttpMethod.Get.Method)
{
        // The action is a Get
}

获取Get和Post

string method = HttpContext.Request.HttpMethod.ToUpper();

您也可以使用:HttpContext.Current.Request.RequestType

https://msdn.microsoft.com/en-us/library/system.web.httprequest.requesttype (v = vs.110) . aspx

我通过使用HttpContextAccessor接口来检索当前的HTTP动词,该接口被注入到构造函数中,例如

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

用法:

_httpContextAccessor.HttpContext.Request.Method

HttpContext.Current.Request.HttpMethod返回字符串,但最好使用enum HttpVerbs。似乎没有内置方法来获取当前动词作为enum,所以我为它编写了helper

辅助类

public static class HttpVerbsHelper
    {
        private static readonly Dictionary<HttpVerbs, string> Verbs =
            new Dictionary<HttpVerbs, string>()
            {
                {HttpVerbs.Get, "GET"},
                {HttpVerbs.Post, "POST"},
                {HttpVerbs.Put, "PUT"},
                {HttpVerbs.Delete, "DELETE"},
                {HttpVerbs.Head, "HEAD"},
                {HttpVerbs.Patch, "PATCH"},
                {HttpVerbs.Options, "OPTIONS"}
            };
        public static HttpVerbs? GetVerb(string value)
        {
            var verb = (
                from x in Verbs
                where string.Compare(value, x.Value, StringComparison.OrdinalIgnoreCase) == 0
                select x.Key);
            return verb.SingleOrDefault();
        }
    }

应用程序的基本控制器类

public abstract class BaseAppController : Controller
    {
        protected HttpVerbs? HttpVerb
        {
            get
            {
                var httpMethodOverride = ControllerContext.HttpContext.Request.GetHttpMethodOverride();
                return HttpVerbsHelper.GetVerb(httpMethodOverride);
            }
        }
}