我正在尝试在Blazor服务器端创建一个httpclient,这将在每次调用webapi时产生最少的配置工作量。
基本上我想实现以下目标:
要开始,我在启动时创建了以下内容:
services.AddHttpClient<myapp.server.api.swaggerClient>(c =>
{
c.BaseAddress = new Uri("https://api.myapp.com/");
AzureADB2COptions opt = new AzureADB2COptions();
Configuration.Bind("AzureAdB2C", opt);
IConfidentialClientApplication cca =
ConfidentialClientApplicationBuilder.Create(opt.ClientId)
.WithRedirectUri(opt.RedirectUri)
.WithClientSecret(opt.ClientSecret)
.WithB2CAuthority(opt.Authority)
.WithClientName("myWebapp")
.WithClientVersion("0.0.0.1")
.Build();
IHttpContextAccessor pp;
string signedInUserID = context.User.FindFirst(ClaimTypes.NameIdentifier).Value;
new MSALStaticCache(signedInUserID, pp.HttpContext).EnablePersistence(cca.UserTokenCache);
var accounts = cca.GetAccountsAsync().Result;
AuthenticationResult result = null;
result = cca.AcquireTokenSilent(opt.ApiScopes.Split(' '), accounts.FirstOrDefault()).ExecuteAsync().Result;
c.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
});
我希望能够以这种方式在我的视图中调用我的api:
myapp.server.api.swaggerClient t = new myapp.server.api.swaggerClient();
currentCount = t.WeatherForecastAsync().Result.FirstOrDefault().Summary;
调用swaggerclient的新实例需要我指定一个httpclient,所以我希望注入在全局级别配置的httpclient,该类型可以自动注入。
我需要帮助的部分:
答案 0 :(得分:0)
关于第一个问题,在您的视图中插入Web API HttpClient:
@inject myapp.server.api.swaggerClient MyClient
,然后在代码块中:
currentCount = MyClient.WeatherForecastAsync().Result.FirstOrDefault().Summary;
您应该能够调试AddHttpClient
内部的代码。