我正在将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?}");
});
}
}
我的配置中缺少什么?
答案 0 :(得分:3)
更新
您的问题还表明,您可能遵循了错误的“入门指南”,因为调用app.AddNLogWeb();
仅适用于Asp.Net Core 1 ,而您很有可能使用版本 2 。请参考文档的正确部分:
原始答案
错误很明显是自言自语。您尚未将应用程序配置为使用会话。
在您的Startup.cs
-ConfigureServices()
方法中,添加以下行:
public void ConfigureServices(IServiceCollection services)
{
/*other config...*/
services.AddSession();
}
然后在Configure()
方法中添加以下内容:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSession(); //<--- add this line
app.UseHttpContextItemsMiddleware();
app.UseMvc();
}
这应该可以解决该异常。
这是文档中的说明:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1
答案 1 :(得分:0)
如果完全不可能使用在UseNLog
中调用Program.cs
的推荐方法:
https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2#4-update-programcs
然后,您也可以执行以下操作:
using Microsoft.Extensions.DependencyInjection;
using NLog.Extensions.Logging;
using NLog.Web;
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSession(); // After AddMvc()
services.AddHttpContextAccessor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseSession(); // Before UseMvc()
app.UseMvc();
app.ApplicationServices.SetupNLogServiceLocator();
loggerFactory.AddNLog();
}
}
另请参阅http://www.jiodev.com/aspnet/core/fundamentals/app-state
答案 2 :(得分:0)
选中以放入Startup.cs
// Configure Method app.UseRouting(); // AppService Method services.AddDistributedMemoryCache(); services.AddSession();