我正在针对 Blazor 3.0.0-preview4-19216-03 的客户端 Blazor 应用程序中进行测试
Razor 页面:
@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();
}
}
依赖注入(inject):
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
调用中。
更新
如果我在 Chrome 的 WASM 调试器中调试 WebCrawler 服务,他会发出请求
但是响应部分是空的:
最佳答案
从客户端应用程序,您只能访问您自己的来源或支持 CORS 的站点。
为了验证这是您的问题,您可以尝试 https://postman-echo.com/response-headers?foo1=bar1&access-control-allow-origin=*
,即可能有用。
但它只适用于该站点。您通常无法控制响应 header 。这不是解决办法。
因此,Blazor 客户端对于网络爬虫来说不是一个好的平台。 这同样适用于 JS 或 WASM 上的任何应用。
Blazor 服务器端应该没有问题。或者使用 Web API 服务。
您可以在 Wasm 应用程序中尝试:
@page "/"
@inject HttpClient Http
<h1>Hello, world!</h1>
<div>
<button class="btn btn-primary" @onclick="GetData1">With CORS</button>
<button class="btn btn-primary" @onclick="GetData2">No CORS</button>
</div>
<div>@json</div>
@code
{
string json = ".";
async Task GetData1()
{
json = await Http.GetStringAsync(
"https://postman-echo.com/response-headers" +
"?foo1=bar1&access-control-allow-origin=*");
}
async Task GetData2()
{
json = "Getting w/o CORS... ";
json = await Http.GetStringAsync(
"https://postman-echo.com/response-headers?foo1=bar1");
}
}
关于c# - Blazor HttpClient 卡在 GetAsync 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55953929/