在 ASP.NET 5 (MVC 6) 中使用会话

Using sessions in ASP.NET 5 (MVC 6)

我在让会话在我的 MVC 6 项目中工作时遇到问题。

我读了一篇 great article about this,但我无法让 app.UseInMemorySession(); 按照描述在我的 Startup.cs 中工作。

我将 "Microsoft.AspNet.Session": "1.0.0-beta6" 添加到我的 project.json 的依赖项部分并修改了我的 Startup.cs 如下:

我的配置部分如下所示:

public void ConfigureServices(IServiceCollection services)
{
    // Add MVC services to the services container.
    services.AddMvc();
    services.AddSession();
    services.AddCaching();
}

我的配置部分如下所示:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.MinimumLevel = LogLevel.Information;
        loggerFactory.AddConsole();

        // Configure the HTTP request pipeline.

        // Add the following to the request pipeline only in development environment.
        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseErrorPage();
        }
        else
        {
            // Add Error handling middleware which catches all application specific errors and
            // send the request to the following path or controller action.
            app.UseErrorHandler("/Home/Error");
        }

        // Add static files to the request pipeline.
        app.UseStaticFiles();

        // Configure sessions:
        //app.UseInMemorySession();

        // Add MVC to the request pipeline.
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

注意 app.UseInMemorySession(); 被注释掉了,因为如果我启用它,我会收到以下错误:

'IApplicationBuilder' does not contain a definition for 'UseInMemorySession' and no extension method 'UseInMemorySession' accepting a first argument of type 'IApplicationBuilder' could be found (are you missing a using directive or an assembly reference?)

如果我尝试 运行 没有 app.UseInMemorySession(); 的应用程序,我在使用会话时收到以下错误:

An exception of type 'System.InvalidOperationException' occurred in Microsoft.AspNet.Http.dll but was not handled in user code

如有任何关于如何解决此问题的建议,我们将不胜感激:-)

你应该使用:

app.UseSession();

它位于 Microsoft.AspNet.Builder 命名空间中,因此您不需要 Session 命名空间。

参见:https://github.com/aspnet/Session/blob/1.0.0-beta6/src/Microsoft.AspNet.Session/SessionMiddlewareExtensions.cs

看来我需要做两处改动。

首先我需要添加 using Microsoft.AspNet.Session;,我必须更改: app.UseInMemorySession();app.UseSession();Startup.cs.

的配置部分

至少当我这样做时,它开始工作而不会抛出异常。

为任何尝试使用 rc2 的人添加注释,您会收到以下异常。

ILoggerFactory' does not contain a definition for 'MinimumLevel' and no extension method 'MinimumLevel' accepting a first argument of type 'ILoggerFactory' could be found (are you missing a using directive or an assembly reference?)

MinimumLevel 已根据以下重大更改删除: https://github.com/aspnet/Announcements/issues/122

 loggerFactory.MinimumLevel = LogLevel.Information;

该行只需要从您的 rc2+ 代码(和 OP 的代码)中删除。