c# - 使用 cookie 身份验证为 REST 服务设置 MSTest 的最佳方法?
问题描述
背景:我正在使用 ASP.NET Core 3.1,并集成测试需要 cookie 身份验证的 REST 服务。
下面的候选解决方案。
笔记:
- 我使用 vanilla Host 而不是 TestServer 的原因是因为 cookie 的要求。使用 TestServer 时,它会为您提供一个 HttpClient,但客户端不会将 cookie 传回服务器。
- 我还尝试将自定义 HttpClient 与 TestServer 一起使用。这始终生成 System.Net.Sockets.SocketException (无法建立连接,因为目标机器主动拒绝了它。)
using Microsoft.Extensions.Hosting;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Net;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using WebApi; // Contains my Startup.cs
namespace WebApiTest
{
[TestClass]
public class UserTest
{
static IHost HttpHost;
[ClassInitialize]
public static async Task ClassStartup(TestContext context)
{
HttpHost = Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.Build();
await HttpHost.StartAsync();
}
[ClassCleanup]
public static async Task ClassCleanup()
{
await HttpHost.StopAsync();
}
public static HttpContent GetHttpContent(object content)
{
HttpContent httpContent = null;
if (content != null)
{
httpContent = new ByteArrayContent(JsonSerializer.SerializeToUtf8Bytes(content, content.GetType()));
httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
}
return httpContent;
}
public static HttpClient GetCookieHttpClient()
{
SocketsHttpHandler handler = new SocketsHttpHandler
{
AllowAutoRedirect = false,
CookieContainer = new CookieContainer(),
UseCookies = true
};
return new HttpClient(handler);
}
[TestMethod]
public async Task GetUserData_ReturnsSuccess()
{
using (HttpClient client = GetCookieHttpClient())
{
var credentials = new
{
Email = "test@test.com",
Password = "password123",
};
HttpResponseMessage response = await client.PostAsync("http://localhost:5000/api/auth/login", GetHttpContent(credentials));
response = await client.GetAsync(String.Format("http://localhost:5000/api/users/{0}", credentials.Email));
Assert.IsTrue(response.StatusCode == HttpStatusCode.OK);
}
}
}
}
解决方案
HttpClient
是一个瘦客户端;除非您明确告诉它,否则它不会做任何事情。换句话说,它永远不会为您发送 cookie;您必须为请求添加一个标头,其中包含每个请求Cookie
的 cookie 值。测试服务器“客户端”只是设置为向测试服务器代理请求的实例。您应该按照规定使用测试服务器及其客户端,然后添加您使用它发出的请求的标头。HttpClient
Cookie
推荐阅读
- c - 谁能帮我解决这个 CPLEX 模型?
- ontology - 基于其他属性定义一个属性
- java - 在调用 Web 服务 API 时,我收到 HttpResponseException: Conflict
- tensorflow - 在张量流中计算熵的最佳方法是什么
- c# - 为什么 storyboard.target 没有动画?
- polymer-1.0 - GET 请求后 DOM 上的属性未更改
- sql-server - 我似乎无法正确地在 Select 语句中调用存储过程的语法
- javascript - React - 箭头函数与 bind() 和带参数的事件
- javascript - 如何在 GiftedChat 顶部添加早期消息?
- graphviz - 如何布局 Graphviz / dot layout 和 order 问题