How to safely access actionContext.Request.Headers.GetValues if the key is not found?
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()