【问题标题】:HttpContext.User value is null when using httpClient for calling WebApi method in Blazor在 Blazor 中使用 httpClient 调用 WebApi 方法时,HttpContext.User 值为 null
【发布时间】:2021-05-26 15:57:09
【问题描述】:

我正在使用 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

【问题讨论】:

    标签: blazor dotnet-httpclient blazor-server-side asp.net-blazor


    【解决方案1】:

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

    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了解更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-25
      • 1970-01-01
      相关资源
      最近更新 更多