【问题标题】:How can I change a cookie value from a WebMethod?如何从 WebMethod 更改 cookie 值?
【发布时间】:2017-02-03 17:55:00
【问题描述】:
  [WebMethod]
  public static void SetTheme(string theme)
  {
   Guid studentIdentifier = SessionData.LoggedInUser.Identifier;
   Student student = (Student)ItemFactory.GetItem(studentIdentifier);
   student.Theme = theme;
  }

我想在这个 WebMethod 的末尾更改也称为“主题”的 cookie。我怎样才能做到这一点? cookie 必须在此处设置,而不是通过 JavaScript。这是一个要求。谢谢

【问题讨论】:

    标签: cookies asp.net


    【解决方案1】:

    您可以在 webMethod 中访问 HttpContext,然后从那里访问响应对象。

    var response = HttpContext.Current.Response;
    

    HttpResponse 对象允许您访问随响应发送到浏览器的 cookie:

    if(response.Cookies["theme"]!=null)
      response.Cookies["theme"].Value = myValue;
    

    MSDN documentation 很好地解释了它。您也可以使用 HttpContext.Current.Request 访问请求 cookie

    【讨论】:

    • 你说得对,我不得不使用:HttpContext.Current.Response.Cookies["theme"].Value = theme;谢谢。
    猜你喜欢
    • 2018-06-06
    • 1970-01-01
    • 2017-03-27
    • 1970-01-01
    • 2011-06-15
    • 2014-03-31
    • 2015-07-01
    • 1970-01-01
    • 2016-08-15
    相关资源
    最近更新 更多