【问题标题】:Getting a cookie from a WebClient POST request?从 WebClient POST 请求中获取 cookie?
【发布时间】:2014-01-15 15:42:24
【问题描述】:

我正在尝试向设置身份验证 cookie 的 API 控制器发送 POST 请求。我需要检索那个 cookie,但我不确定如何。我有什么:

从服务发送:

  public static Cookie Authenticate(string username, string url) {
        using (var client = new WebClient()) {
            client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            var data = "="+username;
            var test = client.UploadString(url, "POST", data);
            // get cookie here, converted from HttpCookie
            return new Cookie();
        }
    }

在 API 控制器上接收:

    [Route("api/auth")]
    [System.Web.Http.AcceptVerbs("POST")]
    public HttpCookie SetCookie([FromBody] string username) {
        FormsAuthentication.SetAuthCookie(username, true);
        return FormsAuthentication.GetAuthCookie(decrypted, true);
    }

目前,这会返回我认为是 cookie 的字符串表示形式,这对我没有多大好处。如何从 WebClient 捕获 HttpCookie?

【问题讨论】:

    标签: c# asp.net cookies asp.net-web-api webclient


    【解决方案1】:

    WebClient 是一种高级抽象,不会将 cookie 暴露给消费者。

    你有两个选择:

    您可以从 WebClient 派生自己的类,覆盖 GetWebResponse 方法并在此时读取 cookie

    或者你可以直接使用较低级别的类,比如HttpWebRequest

    【讨论】:

      猜你喜欢
      • 2014-08-23
      • 1970-01-01
      • 2021-01-31
      • 2012-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      相关资源
      最近更新 更多