【发布时间】:2021-10-01 15:26:31
【问题描述】:
我正在使用一个 blazor Web 程序集项目,然后是一个 asp.net 核心 Web api 和一个共享项目。当运行我的两个项目并拉起邮递员以执行 GET 请求 https://localhost:5011/api/WebReport/GatherAllReports 时,它会从 blazor Web 程序集命中 ReporterRepository,当它到达第一行 var response 时,它会停留在该行,然后最终经过一个真正的很长一段时间它都在邮递员上说......
System.Threading.Tasks.TaskCanceledException:由于配置的 HttpClient.Timeout 已过 100 秒,请求被取消。
---> System.TimeoutException: 操作被取消。
---> System.Threading.Tasks.TaskCanceledException: 操作被取消。
---> System.IO.IOException: Unable to read data from the transport connection: 由于线程退出或应用程序请求,I/O 操作已中止..
---> System.Net.Sockets.SocketException (995):I/O 操作已 由于线程退出或应用程序请求而中止。
--- 内部异常堆栈跟踪结束 ---
在 System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError 错误,CancellationToken cancelToken)
在 System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.GetResult(Int16 令牌)
在 System.Net.Security.SslStream.ReadAsyncInternal[TIOAdapter](TIOAdapter 适配器,内存`1 缓冲区)
在 System.Net.Http.HttpConnection.FillAsync(布尔异步)
在 System.Net.Http.HttpConnection.ReadNextResponseHeaderLineAsync(布尔异步,布尔 foldedHeadersAllowed)
在 System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage 请求,布尔异步,CancellationToken cancelToken)
---内部异常堆栈跟踪结束---
在 System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage 请求,布尔异步,CancellationToken cancelToken)
在 System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage 请求,布尔异步,布尔 doRequestAuth,CancellationToken 取消令牌)
在 System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage 请求,布尔异步,CancellationToken cancelToken)
在 System.Net.Http.DiagnosticsHandler.SendAsyncCore(HttpRequestMessage 请求,布尔异步,CancellationToken cancelToken)
在 Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancelToken)
在 Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancelToken)
在 System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancellationToken cancelToken)
---内部异常堆栈跟踪结束---
还有更多其他邮件在邮递员中返回。
每当我为我的 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);
}
}
startup.cs 用于 web api:
公共类启动 { 公共启动(IConfiguration 配置) { 配置=配置; }
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 Web 程序集项目中:
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()方法中的性能问题,您的问题中没有包含其内容。 -
抱歉,您的意思有点搞糊涂了。我确实包含了
IReportRepository.GetAll()的内容,请检查ReporterRepository文件GetAll()方法。 @AndrewH -
只是我还是 GET 到
_httpClient.GetAsync("/ReportsPage/GatherAllReports")会造成无限循环?/GatherAllReports的控制器操作调用ReporterRepository.GetAll() -
是的,我也遇到了无限循环,不知道为什么会这样。 @AndrewH
标签: c# asp.net-core-webapi dotnet-httpclient blazor-webassembly