使用 cookie 的 HttpClient (Windows.Web.Http)

HttpClient (Windows.Web.Http) working with cookies

我正在开发 Windows 应用程序,我遇到了一些 cookie 问题。请注意,我正在使用 Windows.Web.Http,而不是系统名称空间 HttpClient。

我正在使用的 API 使用 auth-header 进行身份验证。基本上在 POST 登录后,我需要一种方法来获取返回的 cookie,然后使用这些 cookie 执行后续的 API 调用。我发布了一个我目前拥有的例子,它成功了。我可以在结果对象中看到 cookie。我只是不完全确定从这里去哪里/如何进行。谢谢!有任何想法吗?

using MyApi.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Web.Http;
using Newtonsoft.Json;
using MyApi.Models.Auth;
using MyApi.Models;

namespace MyApi
{
    public class MyService
    {
        private const string MyBaseUrl = "http://api.my.com:3000";
        private readonly HttpClient _httpClient = new HttpClient();

    public async Task<SignInResponse> AttemptLogin(string username, string password)
    {
        if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
            throw new ArgumentException("Username or password is null or empty");

        var uri = new Uri(string.Format("{0}/{1}", MyBaseUrl, "auth/signin"));

        var authSignIn = new Models.Auth.SignInRequest();
        authSignIn.Email = username;
        authSignIn.Password = password;

        var myObject = JsonConvert.SerializeObject(authSignIn);

        // I see the headers in the result object, but I'm not 
        // sure the best way to a) get them out and b) shove them into
        // all of the next calls
        var result = await _httpClient.PostAsync(uri, 
            new HttpStringContent(myObject.ToString(), 
                Windows.Storage.Streams.UnicodeEncoding.Utf8, 
                "application/json"));

        var content = await result.Content.ReadAsStringAsync();
        var successResponse = new SignInResponse();

        try
        {
            successResponse = JsonConvert.DeserializeObject<SignInResponse>(content);
        }
        catch (Exception)
        {
            var failResponse = JsonConvert.DeserializeObject<ErrorResponse>(content);
            throw new Exception(failResponse.message);
        }

        return successResponse;
    }
}
}

您可以使用HttpBaseProtocolFilter.CookieManager,例如:

var filter = new HttpBaseProtocolFilter();
var cookieManager = filter.CookieManager;

var uri = new Uri("http://api.my.com:3000");
foreach (var cookie in cookieManager.GetCookies(uri))
{
    Debug.WriteLine(cookie.Name);
    Debug.WriteLine(cookie.Value);
}

注意,如果 cookie 已经在 HttpCookieContainer 中,cookie 将在下一个请求中自动添加到 http://api.my.com:3000,您无需采取任何行动。

如果您想修改或删除它们,HttpCookieContainer 有方法可以做到。

看看Flurl。它在 Http 位上提供了一个流畅的接口,因此您可以这样说来验证和重用与 cookie 的连接:

using (var fc = new FlurlClient().EnableCookies())
{
  var url = new Url( "http://api.com/endpoint" ) ;

  await url
        .AppendPathSegment("login")
        .WithClient(fc)
        .PostUrlEncodedAsync(new { user = "user", pass = "pass" });

  var page = await url
             .AppendPathSegment("home")
             .WithClient(fc)
             .GetStringAsync();

  // Need to inspect the cookies? FlurlClient exposes them as a dictionary.
  var sessionId = fc.Cookies["session_id"].Value;

}