Mar*_*kCo 8 c# dotnet-httpclient asp.net-core-webapi blazor-webassembly
我正在使用 blazor Web 程序集项目,然后是 asp.net core Web api 和共享项目。当运行我的两个项目并拉起邮递员执行 GET 请求时,https://localhost:5011/api/WebReport/GatherAllReports它会ReporterRepository从 blazor Web 程序集命中,当它命中第一行时,var response它会停留在该行上,然后最终经过很长一段时间后,它会在邮递员上显示...
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 操作已中止。
--- 内部异常堆栈跟踪结束 ---
在System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError错误,CancellationToken取消令牌)
在 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(布尔异步,布尔折叠标题允许)
在 System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage 请求,布尔异步,CancellationToken CancellationToken)
--- 内部异常堆栈跟踪结束 ---
在 System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage 请求,布尔异步,CancellationToken CancellationToken)
在 System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage 请求,布尔异步,布尔 doRequestAuth,CancellationToken CancellationToken)
在System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage请求,布尔异步,CancellationToken取消令牌)
在 System.Net.Http.DiagnosticsHandler.SendAsyncCore(HttpRequestMessage 请求,布尔异步,CancellationToken CancellationToken)
在 Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendAsync(HttpRequestMessage 请求,CancellationToken CancellationToken)
在 Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage 请求,CancellationToken CancellationToken)
在System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage请求,HttpCompletionOption完成选项,布尔异步,布尔emitTelemetryStartStop,CancellationToken取消令牌)
--- 内部异常堆栈跟踪结束 ---
以及邮递员返回的更多其他消息。
每当我调用 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);
}
}
Run Code Online (Sandbox Code Playgroud)
startup.cs对于网络 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();
});
}
Run Code Online (Sandbox Code Playgroud)
}
在我的 Blazor Web 组装项目中:
IReporterRepository.cs:
public interface IReporterRepository
{
Task<List<Reports>> GetAll();
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
您将进入无限循环,因为您的 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
}
}
}
Run Code Online (Sandbox Code Playgroud)