Code how to retrieve cookies in Web Api Calls
Here is an extension method for HttpRequestHeader in Web Api to get Cookies.
public static class HttpRequestHeaderExtension
{
public static string GetCookie(this HttpRequestHeaders header, string name)
{
try
{
var cookies = GetCookies(header);
return cookies.Select(cookie => cookie[name].Value).FirstOrDefault(value => value != null);
}
catch (Exception)
{
return null;
}
}
private static IEnumerable<CookieHeaderValue> GetCookies(HttpRequestHeaders header)
{
var result = new Collection<CookieHeaderValue>();
IEnumerable<string> cookies;
if (header.TryGetValues("Cookie", out cookies))
{
foreach (string cookie in cookies)
{
CookieHeaderValue cookieHeaderValue;
if (CookieHeaderValue.TryParse(cookie, out cookieHeaderValue))
{
result.Add(cookieHeaderValue);
}
}
}
return result;
}
}
}
And to call it on Action filter etc.
Request.Headers.GetCookie("cookieName");
Fork
0 Feedback
You must log in before you can give any feedback
You must log in before you can post a comment


1.11k
0




Mark 'asp.net' tag as 'like'
Mark 'asp.net' tag as 'ignore'