ASP.NET Mvc Api: Set cookie then 302/303 Redirect loses the cookie

I have an API action that returns a HttpResponseMessage.
API address is like: http://localhost/login?authcode=xxx

The API action does some login authentication and redirects the user to either register or the welcome page. Code goes like:

var response = new HttpResponseMessage();
var cookie = new CookieHeaderValue("token", "ThisIsTheTokenNeeded");
response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
response.StatusCode = HttpStatusCode.Found;
response.Headers.Location = new Uri("http://localhost/welcome.html");
return response;

In welcome.html, I use “document.write(document.cookie)” and cannot see the cookie named “token”. Some how it got lost. Could anyone tell me how to get this done or this architecture is not correct after all?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I found the answer. The scope is not set. In my original code the following line is missing.

cookie.Path = "/";

Because redirecting to another page, even if under the same domain, the cookie is not valid across different pages. If path is not set, then the cookie is only valid with the original request targeting http://localhost/login?authcode=xxx

Today I learnt that I need to carefully examine the domain and the path attribute of the cookie before claiming that somebody ate it.

Method 2

My cookies have added Path, but the problem still not resolve.

After a long time, I finally resolve this problem by remove session state config in web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <!--<sessionState cookieless="false" timeout="30" mode="StateServer" stateConnectionString="tcpip=localhost:42424" />-->
  </system.web>
</configuration>

I can add set-cookie header after comments <sessionState>.

I hope this helps you, thanks.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x