c# - Cookie 不会保存在 ASP.NET WebMethod 中

标签 c# asp.net cookies asp.net-web-api webmethod

我试图在 WebMethod 中保存一个 cookie 并在 Page_Load 时检索它。但是,cookie 不会被保存,它会在 Page_Load 事件中返回一个空值。

这是我的代码:

网络方法

[WebMethod]
public static string LoginUser(string email, string pass)
{
    //more code

    var ecookie= new HttpCookie("ecookie");
    ecookie["name"] = "roger";
    HttpContext.Current.Response.Cookies.Add(ecookie);
}

Page_Load

protected void Page_Load(object sender, EventArgs e)
{
    var response = HttpContext.Current.Response;
    if (response.Cookies["ecookie"]["name"] != null) //doesn't go inside this condition since it's null
    {
          string name = response.Cookies["ecookie"]["name"];
    }
}

我做错了什么?

最佳答案

您通过键 userdata 保存 cookie 值,然后通过键 ecookie 检索它。

假设您想要使用 key ecookie 存储 cookie,您的 WebMethod 应该看起来像:

[WebMethod]
public static string LoginUser(string email, string pass)
{
    //more code

    var ecookie= new HttpCookie("ecookie");
    ecookie["name"] = "roger";
    HttpContext.Current.Response.Cookies.Add(ecookie);
}

关于c# - Cookie 不会保存在 ASP.NET WebMethod 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32930506/

相关文章:

c# - 保存对象/序列化

c# - 确定设置源自哪个配置文件?

php - 如何重用 php curl 响应 cookie 并绕过脚本后续执行的登录步骤?

c# - 我应该使用列表吗?

c# - 如何使用 SqlConnectionStringBuilder 从连接字符串中获取数据库名称

javascript - JQuery - 使用 cookie 和窗口宽度在选项卡溢出上进行响应式导航

java - jersey 添加 cookie 然后进行重定向

c# - Entity Framework 在更新时不更改 EnityState

c# - 同时预增量和后增量或混合前后增量

c# - Xamarin Forms 从文本文件中读取结果为空