HttpClient(.Net core 3.1)中的权限集授权标头

问题描述 投票:1回答:1

我正在从.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!我的代码有什么问题?

httpclient .net-core-3.1
1个回答
0
投票

AuthenticationHeaderValue应该这样设置:

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

来源:https://docs.microsoft.com/en-us/dotnet/api/system.net.http.headers.authenticationheadervalue.-ctor?view=netcore-3.1#System_Net_Http_Headers_AuthenticationHeaderValue__ctor_System_String_

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.