diff --git a/src/GeekLearning.Testavior/Environment/ITestEnvironment.cs b/src/GeekLearning.Testavior/Environment/ITestEnvironment.cs index 1bc86cf..75d30d6 100644 --- a/src/GeekLearning.Testavior/Environment/ITestEnvironment.cs +++ b/src/GeekLearning.Testavior/Environment/ITestEnvironment.cs @@ -10,6 +10,8 @@ public interface ITestEnvironment HttpClient Client { get; } + HttpClient CreateClient(bool supportCookies = true); + IServiceProvider ServiceProvider { get; } } } diff --git a/src/GeekLearning.Testavior/Environment/TestEnvironment.cs b/src/GeekLearning.Testavior/Environment/TestEnvironment.cs index 825e71d..805734d 100644 --- a/src/GeekLearning.Testavior/Environment/TestEnvironment.cs +++ b/src/GeekLearning.Testavior/Environment/TestEnvironment.cs @@ -40,7 +40,21 @@ public TestEnvironment(string targetProjectRelativePath = null) } this.Server = this.CreateTestServer(); - this.Client = Server.CreateClient(); + this.Client = this.CreateClient(false); + } + + public HttpClient CreateClient(bool supportCookies = true) + { + if (supportCookies) + { + var client = new HttpClient(new TestMessageHandler(this.Server.CreateHandler())); + client.BaseAddress = this.Server.BaseAddress; + return client; + } + else + { + return this.Server.CreateClient(); + } } protected virtual TestServer CreateTestServer() diff --git a/src/GeekLearning.Testavior/Helpers/Http/TestMessageHandler.cs b/src/GeekLearning.Testavior/Helpers/Http/TestMessageHandler.cs new file mode 100644 index 0000000..f3822e6 --- /dev/null +++ b/src/GeekLearning.Testavior/Helpers/Http/TestMessageHandler.cs @@ -0,0 +1,45 @@ +using Microsoft.Net.Http.Headers; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace GeekLearning.Testavior +{ + public class TestMessageHandler : DelegatingHandler + { + private readonly CookieContainer cookies = new System.Net.CookieContainer(); + + public TestMessageHandler(HttpMessageHandler innerHandler) : base(innerHandler) + { + } + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + request.Headers.Add("Cookie", this.cookies.GetCookieHeader(request.RequestUri)); + + var resp = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); + + if (resp.Headers.TryGetValues("Set-Cookie", out var newCookies)) + { + foreach (var item in SetCookieHeaderValue.ParseList(newCookies.ToList())) + { + if (item.Domain.HasValue) + { + this.cookies.Add(request.RequestUri, new Cookie(item.Name.Value, item.Value.Value, item.Path.Value, item.Domain.Value)); + } + else + { + this.cookies.Add(request.RequestUri, new Cookie(item.Name.Value, item.Value.Value, item.Path.Value)); + } + } + } + + return resp; + } + } +}