在ASP.NET Core 2.1中使用Cookie

编程入门 行业动态 更新时间:2024-10-27 21:17:55
本文介绍了在ASP.NET Core 2.1中使用Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个简单的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

本文发布于:2023-11-09 22:37:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573621.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NET   ASP   Core   Cookie

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!