当前http上下文的Http动词

时间:2011-08-01 12:45:10

标签: c# asp.net http

如何找到用于访问应用程序的http动词(POST,GET,DELETE,PUT)?我正在寻找httpcontext.current,但似乎有任何财产给我信息。感谢

8 个答案:

答案 0 :(得分:39)

使用HttpContext.Current.Request.HttpMethod

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

答案 1 :(得分:6)

HttpContext.Current.Request.HttpMethod

答案 2 :(得分:3)

在ASP.NET CORE 2.0中,您可以使用以下命令获取(或设置)当前上下文的HTTP谓词:

Request.HttpContext.Request.Method

答案 3 :(得分:2)

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

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

答案 4 :(得分:2)

获取Get和Post

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

答案 5 :(得分:1)

在ASP.NET Core v3.1中,我使用HttpContextAccessor接口检索了当前的HTTP动词,该接口注入到构造函数中,例如

private readonly IHttpContextAccessor _httpContextAccessor;

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

用法:

_httpContextAccessor.HttpContext.Request.Method

答案 6 :(得分:0)

HttpContext.Current.Request.HttpMethod返回字符串,但最好使用枚举HttpVerbs。似乎没有构建方法来将currrent动词作为枚举,所以我为它编写了帮助

助手班

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

答案 7 :(得分:0)

if(HttpContext.Request.HttpMethod == HttpMethod.Post.Method){//动作是帖子} if(HttpContext.Request.HttpMethod == HttpMethod.put.Method){//动作是放置},如果(HttpContext.Request.HttpMethod == HttpMethod.DELETE.Method){//动作是DELETE},如果(HttpContext.Request.HttpMethod == HttpMethod.Get.Method){//动作是Get }