我正在从.net core 2.2迁移到3.1。我正在制作一种XUnit测试方法来测试我的控制器。我已经在.net core 2.2项目中成功制作和测试了,但是迁移到3.1之后,似乎无法为我的请求设置授权标头,因此我从我的应用程序中获得了UnAuthorized。
这是我的代码:
[Fact]
public async void InvalidId_UnSuccessFull_GetById()
{
// Arrange
var httpClient = new HttpClient();
var token = await GetAdminAccessToken(); // Sends a login request and fetch a valid token
// httpClient.DefaultRequestHeaders.Add("Authorization",$"Bearer {token}");
httpClient.DefaultRequestHeaders.Authorization=new AuthenticationHeaderValue("Authorization",$"Bearer {token}");
var id = Guid.Empty;
// Act
var response = await httpClient.GetAsync("localhost:5000/Admin/User/{id}");
var message = await ExtractMessage(response);
// Assert
Assert.Contains(PersianErrorMessage.InvalidUserId, message);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}
我调试到httpClient类中,直到sendAsync方法和HttpRequestMessage请求实例没有上面设置的Authorization Header!我的代码有什么问题?
AuthenticationHeaderValue应该这样设置:
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);