I am currently doing this, but it throws an exception if the key is not found.
This snippet is inside of a web api filter that inherits from ActionFilterAttribute
, in the overriden method OnActionExecuting
.
if (actionContext.Request.Headers.GetValues("some_key") != null && actionContext.Request.Headers.GetValues("some_key").First() == "hello") { }
Am I forced to wrap this in a try/catch?
Using the [FromQuery] and [FromHeader] attributes in ASP.NET Core 5 MVC. ASP.NET Core introduces the [FromQuery] and [FromHeader] attributes. While the former is used to pass data via query strings, the latter is used to pass data to the action methods of your controller using request headers.
class MyFilter : System.Web.Http.Filters.ActionFilterAttribute { public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) { IEnumerable<string> values; if (actionContext.Request.Headers.TryGetValues("some_key", out values) && values.First() == "hello") { } } }
Since the release of C# 6.0, here is an alternative syntax to Yuriy Faktorovich's answer where you will get the header value or null as a result in a single line.
actionContext.Request.Headers.SingleOrDefault(x => x.Key == "some_key").Value?.First()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With