这是我最近的代码:
HttpClient authClient = new HttpClient();
authClient.BaseAddress = new Uri("http://localhost:4999/test_db/_session");
authClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var user = new LoginUserSecretModel
{
name = userKey,
password = loginData.Password,
};
HttpResponseMessage authenticationResponse = authClient.PostAsJsonAsync("", user).Result;
Run Code Online (Sandbox Code Playgroud) 我正在使用新的HttpClient来处理我项目的网上冲浪需求; 但是,尽管设置正确,但HttpClient不会将cookie保存到Cookie容器中,并且它始终为EMPTY.
private CookieContainer _cookieContainer = new CookieContainer();
private HttpClient HttpClient { get; set; }
private HttpClientHandler HttpClientHandler { get; set; }
public Initialize()
{
HttpClientHandler = new HttpClientHandler
{
AllowAutoRedirect = true,
UseCookies = true,
CookieContainer = _cookieContainer
};
HttpClient = new HttpClient(HttpClientHandler);
}
public CookieContainer Cookies
{
get { return _cookieContainer; }
set { _cookieContainer = value; }
}
public void TEST()
{
//This is always empty, although I am sure that the site is saving login …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 C# 和 HttpClient 类在 Spotify 登录页面上获取 cookie。但是,当我知道正在设置 cookie 时,CookieContainer 始终为空。我没有发送任何标头,但它仍然应该给我 cookie(s) 因为当我发送一个没有任何标头的 GET 请求时,我得到了 csrf 令牌。这是我的代码:
using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Collections;
using System.Web;
class Program
{
static void Main()
{
Task t = new Task(MakeRequest);
t.Start();
Console.WriteLine("Getting cookies!");
Console.ReadLine();
}
static async void MakeRequest()
{
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
Uri uri = new Uri("https://accounts.spotify.com/en/login/?_locale=en-US&continue=https:%2F%2Fwww.spotify.com%2Fus%2Faccount%2Foverview%2F");
HttpClient client = new HttpClient(handler); …Run Code Online (Sandbox Code Playgroud) 根据MSDN CookieContainer.SetCookies应该
将一个或多个cookie的Cookie实例从HTTP cookie标头添加到CookieContainer以获取特定URI
这意味着它应该适用于多个cookie,但是当我这样做时
_cookieContainer.SetCookies(new Uri("http://localhost"), "a=a;b=b");
Run Code Online (Sandbox Code Playgroud)
然后尝试使用.检索cookie
_cookieContainer.GetCookies(new Uri("http://localhost"));
Run Code Online (Sandbox Code Playgroud)
我只得到一个cookie条目 a=a
我认为可能是cookie头格式错误,所以我手动添加两个cookie使用.Add方法,后来尝试通过调用获取头.GetCookieHeader,我得到完全相同的字符串"a=a;b=b".
我错过了什么,或者我发现了一个.NET错误?我目前正在使用
VS2015 - v14.0.23107.0,
.NET - 4.6 4.6.00081