在Xamarin应用程序中,我试图从使用ModernHttpClient.NativeMessageHandler转移到使用NSUrlSessionHandler,但在使用CookieContainer时遇到了障碍,我试图编写的代码是:
var httpHandler = new NSUrlSessionHandler();
httpHandler.AllowAutoRedirect = false;
httpHandler.CookieContainer = cookieContainer;
return new HttpClient(httpHandler);这不能编译,因为NSUrlSessionHandler没有CookieContainer属性。
发布于 2019-05-08 11:07:58
我最终扩展了nsurlSessionHandler并实现了我的cookieLogic。
示例:
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Autofac;
using Foundation;
using Appname.Mobile;
using Appname.Mobile.Services;
namespace Appname.Mobile.iOS
{
[Preserve]
public class CustomMessageHandler : NSUrlSessionHandler
{
static ICookieStorageService CookiesService { get; set; }
static CookieContainer Container { get; set; }
public KDSHttpClientHandler()
{
CookiesService = App.Container.Resolve<ICookieStorageService>();
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (CookiesService != null)
{
Container = CookiesService.GenerateCookieContainer(request.RequestUri);
CookiesService.ApplyRecentCookie(Container, request);
}
var result = await base.SendAsync(request, cancellationToken);
if (CookiesService != null)
{
var cookieHeaders = result.Headers.Where(h => h.Key.Equals("Set-Cookie", StringComparison.InvariantCultureIgnoreCase)).ToList();
foreach (var header in cookieHeaders)
{
try
{
if (header.Value != null)
{
var cookieParts = header.Value.First().Split(';');
var cookieValue = cookieParts[0].Split('=');
Container.Add(new Cookie(cookieValue[0], cookieValue[1], "/", request.RequestUri.GetBaseDomain()));
CookiesService.UpdateCookies(Container, request.RequestUri);
}
}
catch (Exception ex)
{
App.Logger.Error("CustomMessageHandler.SendAsync.CookieContainer", ex.Message);
}
}
}
return result;
}
}
}发布于 2018-07-20 03:09:29
HttpClientHandler和NSUrlSessionHandler都是HttpMessageHandler的子类并实现了SendAsync()方法。CookieContainer是一个只属于HttpClientHandler的结构,正如您所发现的,它在NSUrlSessionHandler中是不存在的。
在Xamarin.iOS中,您可以直接使用NSHttpCookieStore,这是一个具有自动与NSUrlSessionHandler共享的共享cookie存储的单例。您可以在NSHttpCookieStorage文档中查看SetCookie方法。
示例:
{
foreach (var cookie in NSHttpCookieStorage.SharedStorage.Cookies)
{
Console.WriteLine($"Name: {cookie.Name}, Path: {cookie.Path}"
}
}https://stackoverflow.com/questions/51175748
复制相似问题