我正在开发一个 rest API .net core 2.0,它需要大约 1MB 的 JSON 负载。在检查日志时,我发现请求到操作方法调用之间存在巨大延迟。
日志:
20:05:12.7247|1|INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 POST
20:05:12.7514||INFO|Service.RequestLoggingMiddleware|Middleware Request recieved at 2019-03-12 20:05:12.725
20:05:15.2839|1|INFO|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executing action method
在收到请求和路由到相应操作之间大约有 2 秒的延迟。 我只添加了 Nlog 提供程序、自定义中间件来记录请求接收和中间件管道中的 mvc。
自定义中间件记录请求时间:
public class RequestLoggingMiddleware
{
private readonly RequestDelegate requestDelegate;
private ILogger<RequestLoggingMiddleware> logger;
public RequestLoggingMiddleware(RequestDelegate _requestDelegate,ILogger<RequestLoggingMiddleware> _logger)
{
requestDelegate = _requestDelegate;
logger = _logger;
}
public async Task Invoke(HttpContext context)
{
try {
string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff",CultureInfo.InvariantCulture);
logger.LogInformation("Middleware Request recieved at {0}", timestamp);
await requestDelegate.Invoke(context);
}
catch { }
}
}
配置的中间件管道:
public void Configure(IApplicationBuilder app, IHostingEnvironment
env,ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
env.ConfigureNLog("nlog.config");
loggerFactory.AddNLog();
app.AddNLogWeb();
app.UseMiddleware<RequestLoggingMiddleware>();
app.UseMvc();
}
编辑:我发现延迟与 Json 负载的大小成正比。
public SampleController(ILogger<GroupsValidation1Controller> _logger)
{
logger = _logger;
}
[HttpPost]
public IActionResult Validate([FromBody]JObject inputValue)
{
logger.LogInformation(" method starts ");
///controllerlogic
logger.LogInformation(" method ends");
}
为什么 .Net Core MVC 中间件要花这么多时间?
有没有办法减少中间件的延迟?
我还发现整个请求也被记录下来,尽管它没有配置。我不确定记录整个请求是否需要时间。有什么方法可以禁用它吗?
最佳答案
我认为整个延迟都发生在模型绑定(bind)中。由于 Json 负载很大,模型绑定(bind)到 jobject 类型需要时间。跳过模型绑定(bind)和读取原始请求主体或使用自定义模型而不是 jobject,我能够减少延迟并提高 api 的性能。
关于c# - 请求和操作之间的 Asp.net 核心中间件路由延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55124938/