【发布时间】:2019-01-03 00:44:45
【问题描述】:
我想记录我的应用处理每个请求所花费的时间,以及一些其他信息,例如收到的每个请求的 IP 地址。
我在 Startup.cs 添加了一个 app.Use 步骤 -> 使用依赖注入配置到我的 dbcontext。当以下代码触发并且我的 MVC 管道似乎正确触发时,我没有收到任何错误。
问题是任何涉及 dbcontext 的调用似乎都会退出代码。在下面的示例中,db.PageRequests.Add(pageRequest); 导致代码退出。该页面仍然可以正常呈现,但当然缺少响应附加的任何内容。
我不禁认为这是一个异步/线程问题,但我迷失了想法。我还尝试使 dbcontext 交互同时同步和异步,但它没有帮助。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ApplicationDbContext db)
{
app.Use(async (context, next) =>
{
var sw = new Stopwatch();
sw.Start();
await next.Invoke();
sw.Stop();
PageRequest pageRequest = new PageRequest()
{
ipAddress = context.Connection.RemoteIpAddress.ToString(),
loadTime = sw.ElapsedMilliseconds
};
db.PageRequests.Add(pageRequest); // this code exits and page is rendered. Code below here is never fired.
db.SaveChanges();
await context.Response.WriteAsync("<p>" + sw.ElapsedMilliseconds.ToString() + "<p>");
await context.Response.WriteAsync("<p>" + context.Connection.RemoteIpAddress + "<p>");
await context.Response.WriteAsync("<p>" + context.Request.Host + context.Request.Path + context.Request.QueryString + "<p>");
});
// other app.use statements here
}
【问题讨论】:
标签: entity-framework logging asp.net-core-mvc configure asp.net-core-2.1