【发布时间】:2018-12-03 09:38:56
【问题描述】:
我正在将 ASP.Net 应用程序迁移到 ASP.Net Core。主要设置 NLog 可以正常工作。 现在我想将会话 ID 与日志消息一起记录。为此我添加了 - Microsoft.AspNetCore.Session - NLog.Web.AspNetCore 来自 NuGet。
会话在启动中被激活,我在代码中获得会话 ID。
在Startup.cs 中的NLog on GitHub 之后应该添加
//add NLog.Web
app.AddNLogWeb();
这没有任何意义,因为该方法已被标记为过时。
但是,无论有没有该行,NLog 都不会对日志文件产生正确的输出。仅记录以下内容:
2018-12-03 09:59:42.6111 Warn Exception in layout renderer. Exception: System.InvalidOperationException: Session has not been configured for this application or request.
at Microsoft.AspNetCore.Http.DefaultHttpContext.get_Session()
at NLog.Web.LayoutRenderers.AspNetSessionIdLayoutRenderer.DoAppend(StringBuilder builder, LogEventInfo logEvent)
at NLog.LayoutRenderers.LayoutRenderer.RenderAppendBuilder(LogEventInfo logEvent, StringBuilder builder)
目标配置如下:
<target archiveAboveSize="10000000"
xsi:type="File"
fileName="${basedir}/logs/SystemOut.log"
archiveFileName="${basedir}/logs/SystemOut_${shortdate}.{#}.log"
archiveEvery="Day"
archiveNumbering="Rolling"
maxArchiveFiles="50"
layout="[${date:format=dd\.MM\.yyyy\-HH\:mm\:ss}] [${level}] [${callsite}] [${aspnet-sessionid}] [Client:${event-context:item=clientId}] [User:${aspnet-user-identity}] Url: ${aspnet-request-url} Action: ${aspnet-mvc-action} ${message} ${exception}"
autoFlush="true"
name="sysout" />
这里是Startup.cs的内容:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
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.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(120);
options.Cookie.HttpOnly = true;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
我的配置中缺少什么?
【问题讨论】:
-
这有关于如何在添加 nuget 后设置会话的说明。 docs.microsoft.com/en-us/aspnet/core/fundamentals/…
-
也许我的描述具有误导性。 会话被激活我的意思是 app.UseSessions() 被调用。
-
您可能遵循了错误的入门指南,因为 asp.net core 2 部分不包含
app.AddNLogWeb();调用。请参阅:github.com/NLog/NLog.Web/wiki/…。我也相应地更新了我的答案
标签: c# asp.net asp.net-core nlog