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



我使用httpClient进行web API调用,但在使用HTTP客户端调用web API方法时无法获得HTTP上下文用户值。但我可以得到它调用一个方法在使用ajax请求从js。

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附加安全方案以获取更多信息

最新更新