Vladimirs
Vladimirs

Reputation: 8599

Not able to set cookie from action

I have ASP.NET MVC application hosted along with ASP.NET WebApi application at localhost and localhost/api and I wan't to set a cookie when one action of ASP.NET WebApi called.

I tried to set my cookie like that:

response.Headers.AddCookies(new[]
                                        {
                                            new CookieHeaderValue("test", "asd")
                                            {
                                                Expires = DateTime.Now.AddDays(1),
                                                Domain = Request.RequestUri.Host,
                                                Path = "/",
                                                HttpOnly = false
                                            }
                                        });

I got that in response headers:

Set-Cookie:test=asd; expires=Thu, 30 Oct 2014 09:53:35 GMT; domain=localhost; path=/

But that cookie is not creating for some reason.

Just for testing purposes I tried to set cookie from ASP.NET MVC application like that:

HttpContext.Response.Cookies.Add(new HttpCookie("test", "asd")
            {
                Expires = DateTime.Now.AddDays(1),
                Domain = HttpContext.Request.Url.Host,
                Path = "/",
                HttpOnly = false
            });

Response headers contain:

Set-Cookie:test=asd; domain=localhost; expires=Thu, 30-Oct-2014 09:56:08 GMT; path=/

But still I can't see that cookie. What I am doing wrong how it could be so these headers are ignored? However, other cookies work fine (e.g. .ASPXAUTH).

Upvotes: 1

Views: 3846

Answers (1)

Svein Fidjestøl
Svein Fidjestøl

Reputation: 3206

You can't set cookies on localhost, at least not with Chrome.

You need at least a two part name, e.g. mytestsite.local, or you need to set

Domain = null

in the C# code.

Upvotes: 6

Related Questions