我有一个简单的ASP.NET Core 2.1应用程序,该应用程序应该设置然后读取cookie.
I have a simple ASP.NET Core 2.1 application which is supposed to set and then read a cookie.
每当我尝试读取cookie时,它都会返回null.在浏览器的检查工具中进一步查看,我找不到它.
Whenever I try to read the cookie it returns null. Looking further in the browser's inspect tool I am unable to find it.
我想出了一个小实现,以查看是否可以弄清发生了什么,但是它不起作用..
I came up with this small implementation to see if I can sort out whats going on, but it is not working..
public async Task<IActionResult> Contact(Contato contato) { await email.SendAsync(contato); var option = new CookieOptions(); option.Expires = DateTime.Now.AddMinutes(10); Response.Cookies.Append("EmailEnviado", "true", option); var boh = Request.Cookies["EmailEnviado"]; return RedirectToAction("Contact"); }通过调试器检查的变量boh为空,即使它是在前一行中编写的.
The variable boh, when inspected through the debugger is null, even though it was written in the previous line.
推荐答案第一次设置Cookie后,您将无法立即读取它.一旦响应创建了cookie,您就可以读取它.考虑一下:
You won't be able to read the cookie right after you set it the first time. Once the cookie is created by the response, you will be able to read it. Consider this:
public async Task<IActionResult> OnPostCreateAsync() { var option = new CookieOptions(); option.Expires = DateTime.Now.AddMinutes(10); Response.Cookies.Append("Emailoption", "true", option); return RedirectToPage(); }然后您可以在Get方法中读取cookie:
And then you can read the cookie in the Get method:
public void OnGet() { var boh = Request.Cookies["Emailoption"]; }更多推荐
在ASP.NET Core 2.1中使用Cookie
发布评论