簡體   English   中英

無法在ASP.Net vNext項目中使用會話

[英]Unable to use session in ASP.Net vNext Project

我有一個使用Session的ASP.Net vNext項目。 但是我在嘗試獲取/設置會話中的值時收到此錯誤。

Microsoft.AspNet.Http.Core.dll中出現“System.InvalidOperationException”類型的異常,但未在用戶代碼中處理

附加信息:尚未為此應用程序或請求配置會話。

這是我的控制器方法:

    [AllowAnonymous]
    [HttpGet("/admin")]
    public IActionResult Index()
    {
        if (Context.Session.GetString("UserName") == null) // error thrown here
        {
            return RedirectToAction("Login");
        }

        return View();
    }

我在我的project.json文件中添加了KVM軟件包"Microsoft.AspNet.Session": "1.0.0-beta3" ,並將我的應用程序配置為通過我的Startup.cs使用session,如下所示:

public void ConfigureServices(IServiceCollection services)
{
    // code removed for brevity
    services.AddCachingServices();
    services.AddSessionServices();
}

public void Configure(IApplicationBuilder app)
    {
        app.UseMvc();
        app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(30));
    }

我查看了Github上的vNext文檔,但它沒有提供有關ASP.Net會話的大量信息。 我究竟做錯了什么?

所以我想出來了。 實際上修復非常簡單。 由於ASP.Net將中間件順序添加到請求管道中,我所需要做的就是在使用MVC之前使用會話中間件。 更多信息: https//stackoverflow.com/a/29569746/832546

固定代碼:

public void Configure(IApplicationBuilder app)
{
    app.UseInMemorySession(configure: s => s.IdleTimeout = TimeSpan.FromMinutes(30));
    app.UseMvc();
}

感謝@acrhistof鏈接幫助。

因此,如果您正在使用RC1:在project.json中添加這些依賴項:

 "Microsoft.AspNet.Session": "1.0.0-rc1-final",
 "Microsoft.Extensions.Caching.Memory": "1.0.0",

在Startup.cs文件中:

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

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
     app.UseSession(); //outside of dev  if (env.IsDevelopment())
     ....
     }

似乎事情再次發生了變化,眾所周知的ASP.NET會話必須在rc1中進行不同的配置。 (沒有UseInMemorySession()或其他AppBuilder方法與Session相關,現在它被添加為服務)。

通常,必須安裝,配置和使用Session 所有這些步驟都是新的,有點不尋常。 而且,它取決於Cache:

Session建立在IDistributedCache ,因此您也必須配置它,否則您將收到錯誤。

上面的引用來自ASP.NET 5文檔。 您需要做的就是在這里描述: https//docs.asp.net/en/latest/fundamentals/app-state.html#installing-and-configuring-session

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM