我想保存Activity.Current?.Id ?? HttpContext.TraceIdentifier到数据库中,因为这是用户在默认错误视图中看到的请求 ID。但如何呢?HttpContext在startup.cs 中不可用,我尝试在LayoutRenderer中访问HttpContext未成功。
HomeController 中的错误方法
public IActionResult Error()
{
var model = new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier };
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
我尝试过布局渲染器
namespace Copacking.Web.Utils
{
[LayoutRenderer("requestid")]
public class NLogRequestIdLayoutRenderer : LayoutRenderer
{
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
builder.Append(Activity.Current?.Id ?? HttpContext.TraceIdentifier);
}
}
}
Run Code Online (Sandbox Code Playgroud)
但我收到HttpContext错误,因为需要对象引用。
我该如何解决它?在Nlog.config文件中${aspnet-traceidentifier}正在工作,但${activityid}变量为空:/
您可以使用https://www.nuget.org/packages/NLog.Web.AspNetCore执行以下操作:
layout="${activityid:whenEmpty=${mdlc:item=RequestId:whenEmpty=${aspnet-TraceIdentifier}}}"
Run Code Online (Sandbox Code Playgroud)
请记住在 NLog.config 中包含以下内容:
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5870 次 |
| 最近记录: |