【问题标题】:aspnet-sessionId not working for Asp.Net Coreaspnet-sessionId 不适用于 Asp.Net Core
【发布时间】: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?}");
        });
    }
}

我的配置中缺少什么?

【问题讨论】:

标签: c# asp.net asp.net-core nlog


【解决方案1】:

更新

您的问题还表明,您可能遵循了错误的“入门”指南,因为调用 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

【讨论】:

  • 也许我的描述具有误导性。随着会话被激活,我的意思是 app.UseSessions() 被调用。所以不幸的是,这不是一个解决方案。
  • 请仔细阅读。我没有取消 AddNLogWeb()。此方法已过时。我刚刚提到,不管有没有电话,它都不起作用。
  • 我没有说你使用过它,但你可能使用了错误的入门指南,因此可能会遵循错误的说明,因为AddNLogWeb 在最新的指令集中不存在.
【解决方案2】:

如果在Program.cs中调用UseNLog的推荐方法完全不可能:

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

【讨论】:

  • NLog 本身作为记录器工作。唯一的问题是${aspnet-sessionid} 不会被正确评估。
【解决方案3】:

检查以放入 Startup.cs

// 配置方法
app.UseRouting();


// 应用服务方法
services.AddDistributedMemoryCache();
服务.AddSession();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 2018-06-05
    • 1970-01-01
    • 2019-12-23
    相关资源
    最近更新 更多