1

I am generating a token in web api using FormsAuthenticationTicket, like that:

var user_json_str = new JavaScriptSerializer().Serialize(user);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
    user.UserId,
    DateTime.Now,
    DateTime.Now.AddMinutes(30), false,
    user_json_str, FormsAuthentication.FormsCookiePath);

string encTicket = FormsAuthentication.Encrypt(ticket);//ENCRYPT THE TICKET

after that, I try to return it to the user in the response header like that:

HttpContext.Current.Response.Cookies.Add(new HttpCookie("encTicket", encTicket));

I found the cookie in the client after that.

I read somewhere, that it's not suggested to use web api like that, so I tried this way:

string encTicket = FormsAuthentication.Encrypt(ticket);//ENCRYPT THE TICKET
HttpResponseMessage ans = new HttpResponseMessage();
ans = new HttpResponseMessage(HttpStatusCode.OK);
ans.Content = new StringContent("Logged");
ans.Headers.AddCookies(new[] { new CookieHeaderValue("encTicket", encTicket) });
return ans;

this time the cookie didn't appear in the client ( I tried to read it using document.cookie in the chrome console).

what is the correct way to send cookie in the response header from web api?

5
  • See stackoverflow.com/questions/18513818/… Commented Aug 29, 2014 at 14:59
  • but If I print in the console: document.cookie it already shows all the cookies that present on the page. I dont think $cookie will show me other hidden cookies. Commented Aug 29, 2014 at 15:04
  • I tried what you suggested anyway, and as I thought, the cookie is undefined. my problem is not to read the cookie, but to make sure that it come to the client Commented Aug 29, 2014 at 15:17
  • Check the response headers, is it showing up there? Commented Aug 29, 2014 at 15:58
  • when I read the response using 'Network' tab of chrome yes it shows. but in javascript it is abscent Commented Aug 30, 2014 at 17:39

1 Answer 1

0

Did you try the following ?

ans.Headers.AddCookies(new[] { new CookieHeaderValue("encTicket", encTicket)
{
  Expires = new DateTimeOffset( DateTime.Now.AddYears(1)),Path = "/"
} });
Sign up to request clarification or add additional context in comments.

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.