相关疑难解决方法(0)

从注入 DI 的 IHttpClientFactory 获取名称 HttpClient

在 Blazor 中,我设置了两个 HttpClient。一份用于我的 API,一份用于 MS Graph API。Graph API 是新的,它迫使我找到一种将命名的 httpclient 注入到我的服务中的方法。

这是Main中的所有代码

public class Program
{
    public static async Task Main(string[] args)
    {
        var b = WebAssemblyHostBuilder.CreateDefault(args);
        b.RootComponents.Add<App>("app");

        var samsonApiUrl = new Uri(b.HostEnvironment.BaseAddress + "api/");

        b.Services.AddHttpClient("SamsonApi",client => 
        {
           client.BaseAddress = samsonApiUrl;
           // add jwt token to header
           // add user agent to header
        }).AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
        
        b.Services.AddTransient<GraphCustomAuthorizationMessageHandler>();
        b.Services.AddHttpClient<GraphHttpClientService>("GraphAPI",
                client => client.BaseAddress = new Uri("https://graph.microsoft.com/"))
            .AddHttpMessageHandler<GraphCustomAuthorizationMessageHandler>();
        
        b.Services.AddScoped(provider => provider.GetService<IHttpClientFactory>().CreateClient("SamsonApi"));
        b.Services.AddScoped(provider => provider.GetService<IHttpClientFactory>().CreateClient("GraphAPI"));
        
        b.Services.AddMsalAuthentication<RemoteAuthenticationState, CustomUserAccount>(options =>
        {
            b.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
            options.ProviderOptions.DefaultAccessTokenScopes.Add("1c8d4e31-97dd-4a54-8c2b-0d81e4356bf9/API.Access");
            options.UserOptions.RoleClaim = "role"; …
Run Code Online (Sandbox Code Playgroud)

c# dependency-injection scrutor blazor-webassembly

1
推荐指数
1
解决办法
5227
查看次数