客户端上的HttpClientFactory和WebAssembly .Net核心托管崩溃

时间:2020-06-10 21:01:55

标签: json asp.net-core .net-core blazor webassembly

我希望从同样由ASP.Net Core托管的Blazor WebAssembly调用外部Web服务。

背景信息夫妇

  1. 其中很多是基于Tim Corey在普通Blazor Server中HtmlClient上的视频,该视频可以正常工作。

https://www.youtube.com/watch?v=cwgck1k0YKU

  1. Microsoft有添加客户端的文档,但是到目前为止,当它调用sendasync时,它会退出

https://docs.microsoft.com/en-us/aspnet/core/security/blazor/webassembly/additional-scenarios?view=aspnetcore-3.1

以下是一些正在尝试的代码。我是Blazor的新手,喜欢它。

更新:2020/6/11 我创建了一个GitHub示例-包含了这个问题-实际上它要多一些,因为它允许使用多个ASP.Net代码宿主,但仅当第二个宿主通过原始宿主传递时才有效

https://github.com/HStewartGitHome/BlazorMultiServer

Stewart

public static async Task Main(string[] args)
{
    string uri = "https://www.metaweather.com/api/";
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    builder.RootComponents.Add<App>("app");

    builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

    builder.Services.AddHttpClient("ServerAPI",
                     client => client.BaseAddress = new Uri(uri))
                    .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

    builder.Services.AddTransient(sp => sp.GetRequiredService<IHttpClientFactory>()
                    .CreateClient("ServerAPI"));

    await builder.Build().RunAsync();
}

protected override async Task OnInitializedAsync()
{
    var request = new HttpRequestMessage(HttpMethod.Get,
        "location/2471217/");

    var client = _clientFactory.CreateClient("ServerAPI");

    HttpResponseMessage response = await client.SendAsync(request);

    if (response.IsSuccessStatusCode)
    {
        forecast = await response.Content.ReadFromJsonAsync<WeatherForecastModel>();
        errorString = null;
    }
    else
    {
        errorString = $"There was an error getting our forecast: { response.ReasonPhrase }";

    }
}

0 个答案:

没有答案