Nat Webb Nat Webb - 1 year ago 81
C# Question

Is there a better way to get a cookie value in ActionFilterAttribute?

I have an ActionFilterAttribute that needs to get a cookie value from the request. Here's the relevant code:

List<CookieState> cookies = actionContext.Request.Headers.GetCookies("NameOfTheCookieIWant").FirstOrDefault().Cookies.ToList();

if (cookies == null)
throw new ArgumentNullException("cookie");

string value = "";
cookies.ForEach(cookie => {
if (cookie.Name == "NameOfTheCookieIWant") {
value = cookie.Value;

So I have to go into the headers and get the cookie header that contains the name of the cookie I want. But this gives me a collection of CookieHeaderValues, so I have to take the first of these, which itself contains a Cookies property which is a collection of CookieStates. I turn this collection into a list and run a forEach on it until I find the CookieState whose name matches the name of the cookie I want, then save off the value of that CookieState.

It seems crazy to me that I need to go through so much just to get a cookie value. Surely there's a better, more direct way to get one particular cookie, whose name I know, and its value?

Answer Source
   cookie = actionContext.Request.Headers.GetCookies("NameOfTheCookieIWant").FirstOrDefault();

        if (cookie != null)
             string val = cookie["NameOfTheCookieIWant"].Value;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download