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

4

我在我的MVC 6项目中遇到了会话(sessions)无法正常工作的问题。

我读过一篇很棒的文章,但是我不能像描述的那样在我的Startup.cs中使app.UseInMemorySession();正常工作。

我在project.json文件的依赖项部分添加了"Microsoft.AspNet.Session": "1.0.0-beta6"并修改了我的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

用户代码未处理InvalidOperationException

欢迎提供解决此问题的任何建议 :-)


1
你尝试过检查源代码并直接引用吗?你正在尝试使用的方法在Microsoft.AspNet.Builder.SessionMiddlewareExtensions中。你是否添加了Microsoft.AspNet.Builder的using语句?(它可能是默认存在的,但最好确认一下) - mason
3个回答

4

你说得对 - 我晚了56秒,发了一个类似的回答 :-) - Gertsen

0

为了帮助那些尝试使用rc2的人,这里提供一个注意事项。你会遇到以下异常:

ILoggerFactory' 不包含 'MinimumLevel' 的定义,也没有接受类型为 'ILoggerFactory' 的第一个参数的 'MinimumLevel' 扩展方法可以找到(是否缺少 using 指令或程序集引用?)

根据以下重大变更,MinimumLevel已被移除: https://github.com/aspnet/Announcements/issues/122

 loggerFactory.MinimumLevel = LogLevel.Information;

你的代码(和 OP 的代码)只需要删除那一行就可以在 rc2+ 上运行了。


0

看起来我需要做两个更改。

首先,我需要添加using Microsoft.AspNet.Session;,然后我必须在Startup.cs的Configure部分中将: app.UseInMemorySession(); 更改为 app.UseSession();

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接