2

I have a JavaScript client that sets a cookie using

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2019 12:00:00 UTC";

I want to read this cookie on server side using ASP.NET Web API (running on .NET 4.5) but when I inspect request object, I do not see the cookie.

0

3 Answers 3

2

I'm not sure which version of Asp.Net you are referring to but according to:

https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-cookies

You can retrieve cookies using something like:

var userName = Request.Headers.GetCookies("userName").FirstOrDefault()?["userName"].Value;

In a web api 2 controller you will also need a reference to System.Net.Http.

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to use cookies in any action filters (authorization for example), please use the below code to access to them.

public override void OnAuthorization(HttpActionContext context)
{
    var cookie = context.Request.Headers.GetCookies("your-cookie-name").FirstOrDefault();
}

Comments

0

1.if you are want to get cookie value in service then you can use this:-

service Class

public class CookieService : ICookieService
 {
     private readonly IHttpContextAccessor _contextAccessor;

     public CookieService(IHttpContextAccessor contextAccessor)
     {
         _contextAccessor = contextAccessor;
     }
     public string GetCookieValue()
     {
         string cookieValue = _contextAccessor.HttpContext.Request.Cookies["your Cookie Name"];

         return cookieValue ?? string.Empty;
     }
 }

Interface:-

public class ICookieService
{
 string GetCookieValue();
}

and you should have to add inject dependency in you startup.cs class for IHttpContextAccessor

 Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

2.if you want to get cookie value in controller then you can use this:-

var cookieValue = HttpContext.Request.Cookies["your cookie value"].FirstOrDefault()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.