asp.net-core-mvc

How can I check for a response cookie in Asp.net Core MVC (aka Asp.Net 5 RC1)?


I'm converting a web forms application to asp.net core mvc. In my web forms application sometimes after I set some response cookies other code needs to see if they were set, and if so, access the cookie's properties (i.e. value, Expires, Secure, http). In webforms and MVC 5 it's possible to iterate over the cookies and return any particular cookies like so (old school I know)

       for(int i = 0; i < cookies.Count; i++) {
            if(cookies[i].Name == cookieName) {
                return cookies[i];
            }
        }

But the interface for accessing response cookies in asp.net core mvc looks like this:

response cookies interface

Based on this interface I don't see a way to check to see if a response cookie exists and obtain it's properties. But there has gotta be some way to do it?

In an action method I tried setting two cookies on the response object and then immediately trying to access them. But intellisense doesn't show any methods, properties or indexers that would allow me to access them:

enter image description here

For a moment, I thought that perhaps I could use Response.Cookies.ToString(); and just parse the information to find my cookie info, but alas, the ToString() call returns "Microsoft.AspNet.Http.Internal.ResponseCookies" because the object doesn't override the default implementation.

Just for fun I also checked the current dev branch of GitHub to see if the interface has changed since RC1 but it has not. So given this interface, how do I check for the existence of a response cookie and get it's properties? I've thought about trying to hack in via the response headers collection but that seems pretty lame.


Solution

  • Here's how I get the value of a cookie from a Response. Something like this could be used to get the whole cookie if required:

    string GetCookieValueFromResponse(HttpResponse response, string cookieName)
    {
      foreach (var headers in response.Headers.Values)
        foreach (var header in headers)
          if (header.StartsWith($"{cookieName}="))
          {
            var p1 = header.IndexOf('=');
            var p2 = header.IndexOf(';');
            return header.Substring(p1 + 1, p2 - p1 - 1);
          }
      return null;
    }