Reputation: 6291
I am using ASP.Net Core 2 WepAPI controller.
Current version of Chrome(currently 64).
Angular 5 SPA.
Need to work on localhost.
This is controller method:
public class TestController : ControllerBase
{
[HttpGet, Route("api/[controller]/test")]
public async Task<IActionResult> Get()
{
Response.Cookies.Append("testcookie", "testvalue", new CookieOptions
{
Path = "/",
Domain = "localhost",
Expires = DateTime.UtcNow.AddHours(6),
HttpOnly = false,
Secure = false
});
return Ok("Test Ok.");
}
}
And I don't think it matters, but this is my client code.
private async test2() {
const res = await this.http.get('http://localhost:59879/api/test/test').toPromise();
}
When I look in Chrome Console -> Network Tab -> the request line -> Cookies Tab; I see my response cookie(s) but no request cookie. I also do not see request cookie in HttpContext.Request.Cookies
on subsequent requests.
How do I create any kind of cookie,
Assume server is on localhost:59879.
I have tried many iterations of setting the Domain
to localhost, 127.0.0.1, false and excluding it. Tried not specifying CookieOptions
at all, no Expires
, and various combinations of HttpOnly
and Secure
settings to no avail.
These are some resources I have tried.
Update - I see a recent SO that may have the same cause of what I am experiencing.
Upvotes: 4
Views: 3451
Reputation: 3765
This code:
public class TestController : ControllerBase
{
[HttpGet, Route("api/[controller]/test")]
public async Task<IActionResult> Get()
{
Response.Cookies.Append("testcookie", "testvalue", new CookieOptions
{
Path = "/",
Domain = "localhost",
Expires = DateTime.UtcNow.AddHours(6),
HttpOnly = false,
Secure = false
});
return Ok("Test Ok.");
}
}
it will work if you accessing by browser. You trying access via ajax api, it won't work like that. If you analyze the code here:
Response.Cookies.Append("testcookie", "testvalue", new CookieOptions
{
Path = "/",
Domain = "localhost",
Expires = DateTime.UtcNow.AddHours(6),
HttpOnly = false,
Secure = false
});
this response is not access by browser, it access return ajax success.
See here can-an-ajax-response-set-a-cookie thread. Or solution in mapping-header-cookie-string-to-cookiecollection-and-vice-versa.
That's not better approach access API and set-cookies via server, better it just do it on client side as discussion this thread.
Upvotes: 3