https://localhost: 5011 / api / WebReport / GatherAllReports
时,它会从Blazor WebAssembly中的ReporterRepository
进行访问,当它到达第一行var response
时停留在那里,然后最终在很长时间后,在Postman上显示以下错误消息...
System.Threading.Tasks.TaskCanceledException:由于配置的HttpClient.Timeout为100秒已过去而取消了请求。
---> System.TimeoutException:操作被取消。
---> System.Threading.Tasks.TaskCanceledException:操作已取消。
---> System.IO.IOException:无法从传输连接中读取数据:I / O操作因线程退出或应用程序请求而中止。
---> System.Net.Sockets.SocketException(995):I / O操作已中止,因为要么是线程退出,要么是应用程序请求。
--- 内部异常堆栈跟踪结尾 ---
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.GetResult(Int16 token)
at System.Net.Security.SslStream.ReadAsyncInternal[TIOAdapter](TIOAdapter adapter, Memory`1 buffer)
at System.Net.Http.HttpConnection.FillAsync(Boolean async)
at System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(Boolean async, Boolean foldedHeadersAllowed)
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
--- 内部异常堆栈跟踪结尾 ---
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.DiagnosticsHandler.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancellationToken cancellationToken)
--- 内部异常堆栈跟踪结尾 ---
还有很多其他信息在Postman中返回。
为什么每当我调用Web API控制器的路由端点时会发生这种情况?
Web API 控制器:
using BlazorReports.Services; // this contains the `ReporterRepository.cs` file
[Route("api/[controller]")]
[ApiController]
public class WebReportController : ControllerBase
{
private readonly ReporterRepository_repo;
public WebReportController (ReporterRepository repo)
{
_repo = repo;
}
[HttpGet]
[Route("GatherAllReports")]
public async Task<IActionResult> Get()
{
var reportValues = await _repo.GetAll();
return Ok(reportValues);
}
}
用于Web API的startup.cs
:
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; }
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebAPI", Version = "v1" });
});
services.AddDbContext<ReportContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("Default")));
services.AddScoped<IReporterRepository, ReporterRepository>();
services.AddHttpClient<IReporterRepository, ReporterRepository>(client =>
{
client.BaseAddress = new Uri("https://localhost:5011/");
});
services.AddHttpContextAccessor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAPI v1"));
}
app.UseHttpsRedirection();
app.UseCors(opt => opt
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true)
.AllowCredentials());
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
在我的 Blazor WebAssembly 项目中:
IReporterRepository.cs:
public interface IReporterRepository
{
Task<List<Reports>> GetAll();
}
ReporterRepository.cs:
public class ReporterRepository: IReporterRepository
{
private readonly HttpClient _httpClient;
private readonly JsonSerializerOptions _options;
public ReporterRepository(HttpClient httpClient)
{
_httpClient = httpClient;
_options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
}
public async Task<List<Reports>> GetAll()
{
var response = await _httpClient.GetAsync("/ReportsPage/GatherAllReports");
var content = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
throw new ApplicationException(content);
}
var results = JsonSerializer.Deserialize<List<Reports>>(content, _options);
return results;
}
}
IReportRepository.GetAll()
方法中存在性能问题,你的问题中没有包含该方法的内容。 - Andrew HIReportRepository.GetAll()
的内容,请检查ReporterRepository
文件中的GetAll()
方法。@AndrewH - MarkCo_httpClient.GetAsync("/ReportsPage/GatherAllReports")
会创建一个无限循环?/GatherAllReports
的控制器操作调用了ReporterRepository.GetAll()
。 - Andrew H