在 Blazor 中使用 httpClient 调用 WebApi 方法时,HttpContext.User 值为 null

问题描述

我正在使用 httpClient 进行 Web API 调用,但在使用 HTTP 客户端通过 Web API 调用方法时无法获取 HTTP 上下文用户值。但是我可以得到如果调用一个方法来使用来自 js 的 ajax 请求。

client httpClient = new HttpClient();
responseMessage httpResponse = await client.PostAsync(urlValue,httpContent);

在 Web API 方法

UserManager.GetUserAsync(HttpContext.User) // returns null value

解决方法

您的请求未经过身份验证,因此您不能在服务器端拥有用户:

client httpClient = new HttpClient(); 
// this is an anonymous request
responseMessage httpResponse = await client.PostAsync(urlValue,httpContent);

您必须通过注册字符串 HttpClient 来验证您的请求,并使用 BaseAddressAuthorizationMessageHandler 来验证每个请求。

using System.Net.Http;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;

...

builder.Services.AddHttpClient("ServerAPI",client => client.BaseAddress = new Uri("https://www.example.com/base"))
    .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
    .CreateClient("ServerAPI"));

阅读ASP.NET Core Blazor WebAssembly additional security scenarios了解更多信息