3

我有一个 ASP.Net Web API,文档说明我需要将 Auth Token 保存到 cookie,然后将其传回 API 请求。我可以毫无问题地获得 Auth Token。我的问题是保存 cookie 并将其发送回请求的最佳方法是什么。

我在 RequestMessage 中创建了一个 cookie,但在向 API 发出请求时,我找不到将其发回的方法。如何保留登录/cookie 的状态。

非常感谢任何帮助,谢谢。

更新

我现在可以从响应中获取 cookie。我正在使用本教程。http://www.asp.net/web-api/overview/working-with-http/http-cookies让我指出,如果您想使用本教程,请确保更新 Web API 4 的代码库。在下面的方法中,我试图简单地登录和注销。但是,我收到错误代码 500。

 public HttpWebResponse InitializeWebRequest()
        {
            //HttpResponseMessage logoutMessage = await Logout("bla");
            string responseData = string.Empty;
            string url = GetServerEndPoint();
            string authToken = string.Empty;
            string loginInstance = "https://example.com";

            // Create request.
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.CookieContainer = new CookieContainer();

            HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;
            if (response.StatusCode == HttpStatusCode.OK)
            {
                using (System.IO.StreamReader responseReader = new System.IO.StreamReader(request.GetResponse().GetResponseStream()))
                {
                responseData = responseReader.ReadToEnd();
            }

            IList<string> authHeader = responseData.Split('{', '}').ToList();
            authToken = authHeader[2].Substring(13, 25);
            string sessionId = response.Headers.Get(8);
            var nv = new NameValueCollection();
            nv["sid"] = sessionId;
            nv["token"] = authToken;
            CookieHeaderValue cookieVal = new CookieHeaderValue("session", nv);

            // Log out
            string loginInstance2  = "https://example.com";

            HttpWebRequest request2 =             (HttpWebRequest)WebRequest.Create(loginInstance2);
            request2.Method = "POST";
            request2.ContentType = "application/json";
            request2.Headers.Add(nv);

            HttpWebResponse response2 =           (HttpWebResponse)request2.GetResponseAsync().Result;
        }

        return response;
    }
4

1 回答 1

2

哇,多么痛苦!

我不知道为什么我花了这么长时间才弄清楚,但经过数小时和数天,试图让这个愚蠢的身份验证工作我终于弄明白了。这是代码。

一件奇怪的事情是我必须为 cookie 创建标题格式。根据定义,它不是一个真正的 cookie,它是一个该死的标头值。我必须创建标题标题,因为当我从文件中提取 JSON 对象并将其转换为字符串时,我无法从文件中保持格式完整。

public HttpWebResponse InitiliazeWebRequest()
        {
            string responseData = string.Empty;
            string loginInstance = "url + logincreds";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.CookieContainer = new CookieContainer();

            HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;

            if (response.StatusCode == HttpStatusCode.OK)
            {
                using (System.IO.StreamReader responseReader = new System.IO.StreamReader(request.GetResponse().GetResponseStream()))
                {
                    responseData = responseReader.ReadToEnd();
                }

                var toke = response.Headers.Get("authToken");
                JObject o = JObject.Parse(responseData);
                _authToken = (string)o["response"]["authToken"].ToString();

                return response;
            }
            return response;
        }

  public HttpWebResponse LogOut()
        {
            string responseData = string.Empty;
            string loginInstance = "https://www.example.com/logout";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginInstance);
            request.Method = "GET";
            request.ContentType = "application/json";
            request.Headers.Add("Cookie: authToken=" + _authToken);

            HttpWebResponse response = (HttpWebResponse)request.GetResponseAsync().Result;

            if (response.StatusCode == HttpStatusCode.OK)
            {
                using (System.IO.StreamReader responseReader = new System.IO.StreamReader(request.GetResponse().GetResponseStream()))
                {
                    responseData = responseReader.ReadToEnd();
                }

                return response;
            }
            return response;
        }
于 2013-06-24T20:14:39.767 回答