我正在使用一个 blazor Web 程序集项目,后跟一个 asp.net 核心 Web API 和一个共享项目。当运行我的两个项目并拉起邮递员来执行 GET 请求时https://localhost:5011/api/WebReport/GatherAllReports
它会从 blazor Web 程序集击中ReporterRepository
,当它到达第一行时var response
它停留在该行上,然后最终在很长一段时间后它在邮递员上说......
System.Threading.Tasks.TaskCanceledException:由于配置的 HttpClient.超时已过 100 秒,请求被取消。
---> 系统超时异常:操作已取消。
---> 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, CancelToken cancelToken)
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, CancelToken cancelToken)
---内部异常堆栈跟踪---结束
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancelToken cancelToken)
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancelToken cancelToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancelToken cancelToken)
at System.Net.Http.DiagnosticsHandler.SendAsyncCore(HttpRequestMessage request, Boolean async, CancelToken cancelToken)
at Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendAsync(HttpRequestMessage request, CancelToken cancelToken)
at Microsoft.Extensions.Http.Logging.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancelToken cancelToken)
at System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancelToken cancelToken)
---内部异常堆栈跟踪---结束
以及邮递员中返回的更多其他消息。
每当我调用 Web api 控制器的路由终结点时,是否有原因会发生这种情况?
网页 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 APIstartup.cs
:
公共类启动 { 公共启动(配置) { 配置 = 配置; }
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;
}
}
你进入无限循环,因为你的 GetAll() 方法正在调用自身。您的代码应如下所示:
public class ReporterAccessLayer
{
private readonly HttpClient _httpClient;
private readonly JsonSerializerOptions _options;
public ReporterAccessLayer(HttpClient httpClient)
{
_httpClient = httpClient;
_options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
_repository = repository;
}
public async Task<List<Reports>> GetAll()
{
try
{
return await httpClient.GetAsync<List<Reports>>("/ReportsPage/GatherAllReports");
}
catch
{
// do exception handling
}
}
}
您的请求超时,因为您创建了一个无限循环。
WebReportController.Get()
调用ReporterRepository.GetAll()
,进而将HTTP请求发回WebReportController.Get()
,你又回到了起点。对于您似乎正在使用的模式,即控制器操作调用服务类以执行业务逻辑(这是一个很好的模式),您将调用保存报表数据的数据访问层。您实际上并没有在提供的代码中检索任何报表数据。
例如:
public async Task<List<Reports>> GetAll()
{
var reportA = await _reports.GetReportA();
var reportB = await _reports.GetReportA();
// do any further business logic or error handling here
return new List<Reports> { reportA, reportB };
}