Blazor HttpClient卡在GetAsync中 [英] Blazor HttpClient stuck in GetAsync
问题描述
我正在针对Blazor 3.0.0-preview4-19216-03的Client Blazor应用中进行测试
I'm making test in a Client Side Blazor app targeting Blazor 3.0.0-preview4-19216-03
剃须刀页面:
@page "/counter"
@using BlazorServiceTest
@inject IWebCrawlServiceAsync WebCrawler
<h1>Counter</h1>
<p>Current count: @debug</p>
<button class="btn btn-primary" onclick="@IncrementCount">Click me</button>
@functions {
string debug = "";
async void IncrementCount()
{
debug = await WebCrawler.GetWeb();
}
}
依赖注入:
using BlazorServiceTest;
using Microsoft.AspNetCore.Components.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace BlazorServicesTest
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IWebCrawlServiceAsync, WebCrawlServiceAsync>();
}
public void Configure(IComponentsApplicationBuilder app)
{
app.AddComponent<App>("app");
}
}
}
服务:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace BlazorServiceTest
{
public interface IWebCrawlServiceAsync
{
Task<string> GetWeb();
}
public class WebCrawlServiceAsync : IWebCrawlServiceAsync
{
private HttpClient _client;
public WebCrawlServiceAsync(HttpClient client)
{
_client = client;
}
public async Task<string> GetWeb()
{
var response = await _client.GetAsync("https://postman-echo.com/response-headers?foo1=bar1&foo2=bar2");
var result = await response.Content.ReadAsStringAsync();
return result;
}
}
}
每当我单击增量"时,都不会发生任何事情,并且对GetWeb
的服务调用被卡在GetAsync
调用中.
Whenever I click in Increment count nothing happens and the service call to GetWeb
it's stuck in the GetAsync
call.
更新
如果我在Chrome的WASM调试器中调试WebCrawler服务,则会发出他的请求
If I debug the service WebCrawler in Chrome's WASM debugger, he request is being made
但是响应部分为空:
推荐答案
在客户端应用中,您只能访问自己的来源或支持CORS的网站.
From a client-side app you can only acces your own origin or sites that support CORS.
为了验证这是您的问题,可以尝试使用https://postman-echo.com/response-headers?foo1=bar1&access-control-allow-origin=*
,它可能会起作用.
In order to verify that this is your issue, you can try https://postman-echo.com/response-headers?foo1=bar1&access-control-allow-origin=*
, that might work.
但是它仅适用于该站点.通常,您无法控制响应头.这不是解决方法.
But it will only work for that site. You normally have no control over the response headers. It's not a fix.
因此,对于网络爬虫来说,Blazor客户端不是一个好的平台. JS或WASM上的任何应用程序也是如此.
So, Blazor client-side is just not a good platform for a webcrawler. The same goes for any app on JS or WASM.
Blazor服务器端应该没有问题.或使用Web API服务.
Blazor server-side should have no problems. Or use a Web API service.
这篇关于Blazor HttpClient卡在GetAsync中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!