我有一个 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;
}