使用泛型添加 HTTP 客户端 - ASP.NET 核心

Adding HTTP Client with Generics - ASP.NET Core

我有几个客户想要执行相同的行为并且想使用泛型来完成。

不幸的是,我无法编译它。

我收到“类型 t 必须是引用类型才能将其作为泛型类型或方法中的参数 TClient 引用...”。

我不太懂语法。寻找建议。

public static void AddHttpClient<T>(WebAssemblyHostBuilder builder, 
        string apiBaseUrl, string apiScope)
    {
        builder.Services.AddHttpClient<T>(client =>
        {
            client.BaseAddress = new System.Uri(apiBaseUrl);// new Clients.DepartmentClient(apiBaseUrl);
        }
        ).AddHttpMessageHandler(sp =>
        {
            var handler = sp.GetService<AuthorizationMessageHandler>()
            .ConfigureHandler(
                authorizedUrls: new[] { apiBaseUrl },
                scopes: new[] { apiScope }
             );
            return handler;
        });
    }

这应该可以做到。

public static void AddHttpClient<T>(WebAssemblyHostBuilder builder, 
    string apiBaseUrl, string apiScope) where T : class

您收到错误是因为 AddHttpClient 对其泛型类型参数有 class 约束,因此您需要向您的方法添加相同的约束。

完整方法:

public static void AddHttpClient<T>(WebAssemblyHostBuilder builder, 
    string apiBaseUrl, string apiScope) where T : class
{
    builder.Services.AddHttpClient<T>(client =>
    {
        client.BaseAddress = new System.Uri(apiBaseUrl);// new Clients.DepartmentClient(apiBaseUrl);
    }
    ).AddHttpMessageHandler(sp =>
    {
        var handler = sp.GetService<AuthorizationMessageHandler>()
        .ConfigureHandler(
            authorizedUrls: new[] { apiBaseUrl },
            scopes: new[] { apiScope }
         );
        return handler;
    });
}

can read more about type constraints here