簡體   English   中英

“ IApplicationBuilder”不包含“ UseSession”的定義

[英]'IApplicationBuilder' does not contain a definition for 'UseSession'

我正在使用早期使用Core 1.0的ASP.NET Core 2.0構建應用程序。 遷移后,一切似乎都工作正常,但是當我嘗試使用Session方法app.UseSession()它將引發以下錯誤:

“ IApplicationBuilder”不包含“ UseSession”的定義,找不到可以接受類型為“ IApplicationBuilder”的第一個參數的擴展方法“ UseSession”(您是否缺少using指令或程序集引用?)

我嘗試從NuGet安裝ASPNETCore.Session程序包,但無法。

誰能幫助我找到問題的根本原因?

首先將會話服務注入您的ConfigureServices方法:

services.AddSession(options =>
{
      // Set a short timeout for easy testing.
      options.IdleTimeout = TimeSpan.FromSeconds(2400);
      options.Cookie.HttpOnly = true;
});

然后使用app.UseSession(); Configure方法中。

在ASP.NET Core會話不支持通用數據類型的情況下,您需要添加此擴展名

using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

public static class SessionExtensions
{
    public static void Set<T>(this ISession session, string key, T value)
    {
        session.SetString(key, JsonConvert.SerializeObject(value));
    }

    public static T Get<T>(this ISession session,string key)
    {
        var value = session.GetString(key);
        return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
    }
}

並使用它:

public IActionResult SetDate()
{
    // Requires you add the Set extension method mentioned in the article.
    HttpContext.Session.Set<DateTime>(SessionKeyDate, DateTime.Now);
    return RedirectToAction("GetDate");
}

public IActionResult GetDate()
{
    // Requires you add the Get extension method mentioned in the article.
    var date = HttpContext.Session.Get<DateTime>(SessionKeyDate);
    var sessionTime = date.TimeOfDay.ToString();
    var currentTime = DateTime.Now.TimeOfDay.ToString();

    return Content($"Current time: {currentTime} - "
                 + $"session time: {sessionTime}");
}

暫無
暫無

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

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