HttpClient(Windows.Web.Http)使用cookie

时间:2015-07-09 23:44:33

标签: c# cookies windows-phone-8.1 win-universal-app

我正在开发一款Windows应用,但我遇到了一些Cookie问题。请注意,我正在使用Windows.Web.Http,而不是System命名空间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;
    }
}
}

2 个答案:

答案 0 :(得分:4)

您可以使用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有方法可以做到这一点。

答案 1 :(得分:1)

看看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;

}