【问题标题】:How to use Sessions in ASP vNext如何在 ASP vNext 中使用会话
【发布时间】:2015-03-29 15:07:56
【问题描述】:

如何在 ASP MVC 6 中使用会话变量?

我找不到有关如何存储和使用会话变量的工作示例。谁能帮忙?

【问题讨论】:

    标签: iis asp.net-core asp.net-core-mvc


    【解决方案1】:

    将包"Microsoft.AspNet.Session": "1.0.0-beta8"添加到project.json,然后using Microsoft.AspNet.Http;

    在该命名空间内,您有上下文的扩展方法。

    您还需要在Startup.cs 上将其与 DI 一起使用:

    public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddSession();
        }
    

    这是一个示例控制器:

    using Microsoft.AspNet.Http;
    using Microsoft.AspNet.Mvc;
    
    namespace MvcWebApp.Controllers
    {
        [Route("[controller]")]
        public class SomeController : Controller
        {
            public async Task<IActionResult> Edit()
            {
                HttpContext.Session.SetInt("myVar", 35);
            }
        }
    }
    

    【讨论】:

    • 添加项目 nuget 引用并在服务中添加会话后,我收到以下错误:Error CS1061 'IServiceCollection' does not contain a definition for 'AddSession' and no extension method 'AddSession' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?)
    • Beta 8 将 Context 属性重命名为 HttpContext(符合 MVC 5)
    • 嗨@ChristopherHackett,你有一些指向这个重命名的链接吗?
    • 当然 @neel - 记录在 MVC 存储库 github.com/aspnet/Mvc/issues/3165 的这张票中
    【解决方案2】:

    在 github 上的 session repo 上有一个示例:https://github.com/aspnet/Session/tree/release

    你可以通过Controler's Session属性访问会话

    【讨论】:

    • 我试过了,但我得到了这个错误:500 Internal Server Error System.ArgumentException ISessionStore must be specified。
    • 如果我启用 app.UseInMemorySession(); ,我收到另一个错误 500 Internal Server Error System.Exception TODO: Unable to resolve service for type 'Microsoft.Framework.Cache.Distributed.IDistributedCache' 同时尝试激活'Microsoft.AspNet.Session.DistributedSessionStore'。
    • 你启用缓存了吗?示例使用 Redis 缓存
    • 我没有启用缓存。我尝试添加 RedisCache 包,它仍然没有工作。
    • 我设法做到了。它是 services.AddCachingServices(); services.AddSessionServices();
    猜你喜欢
    • 2015-05-17
    • 2016-09-21
    • 1970-01-01
    • 2015-06-30
    • 2015-06-22
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 2012-07-05
    相关资源
    最近更新 更多