Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to safely access actionContext.Request.Headers.GetValues if the key is not found?

Tags:

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?

like image 741
loyalflow Avatar asked Sep 24 '13 15:09

loyalflow


People also ask

How do I read request headers in .NET core?

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.


2 Answers

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")         {          }     } } 
like image 183
Yuriy Faktorovich Avatar answered Sep 23 '22 08:09

Yuriy Faktorovich


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()

like image 27
Jonathan Harrison Avatar answered Sep 24 '22 08:09

Jonathan Harrison