'Http verb of current http context
How do you find the http verb (POST,GET,DELETE,PUT) used to access your application? Im looking httpcontext.current but there dosent seem to be any property that gives me the info. Thanks
Solution 1:[1]
Use HttpContext.Current.Request.HttpMethod.
See: http://msdn.microsoft.com/en-us/library/system.web.httprequest.httpmethod.aspx
Solution 2:[2]
HttpContext.Current.Request.HttpMethod
Solution 3:[3]
In ASP.NET CORE 2.0 you can get (or set) the HTTP verb for the current context using:
Request.HttpContext.Request.Method
Solution 4:[4]
For getting Get and Post
string method = HttpContext.Request.HttpMethod.ToUpper();
Solution 5:[5]
You can also use: HttpContext.Current.Request.RequestType
https://msdn.microsoft.com/en-us/library/system.web.httprequest.requesttype(v=vs.110).aspx
Solution 6:[6]
In ASP.NET Core v3.1 I retrieve the current HTTP verb by using the HttpContextAccessor interface which is injected in on the constructor, e.g.
private readonly IHttpContextAccessor _httpContextAccessor;
public MyPage(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
Usage:
_httpContextAccessor.HttpContext.Request.Method
Solution 7:[7]
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
}
Solution 8:[8]
HttpContext.Current.Request.HttpMethod return string, but better use enum HttpVerbs. It seems there are no build in method to get currrent verb as enum, so I wrote helper for it
Helper class
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();
}
}
base controller class of application
public abstract class BaseAppController : Controller
{
protected HttpVerbs? HttpVerb
{
get
{
var httpMethodOverride = ControllerContext.HttpContext.Request.GetHttpMethodOverride();
return HttpVerbsHelper.GetVerb(httpMethodOverride);
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daniel A. White |
| Solution 2 | spender |
| Solution 3 | Ben Smith |
| Solution 4 | Kishan |
| Solution 5 | AlignedDev |
| Solution 6 | Ciaran Gallagher |
| Solution 7 | DanB |
| Solution 8 | Sel |
