我希望从同样由ASP.Net Core托管的Blazor WebAssembly调用外部Web服务。
背景信息夫妇
https://www.youtube.com/watch?v=cwgck1k0YKU
以下是一些正在尝试的代码。我是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 }";
}
}