[英]'IApplicationBuilder' does not contain a definition for 'UseSession'
I am building an app using ASP.NET Core 2.0 which was earlier using Core 1.0. 我正在使用早期使用Core 1.0的ASP.NET Core 2.0构建应用程序。 After migration everything seems to be working fine but when i try to use Session method
app.UseSession()
then it throws following error: 迁移后,一切似乎都工作正常,但是当我尝试使用Session方法
app.UseSession()
它将引发以下错误:
'IApplicationBuilder' does not contain a definition for 'UseSession' and no extension method 'UseSession' accepting a first argument of type 'IApplicationBuilder' could be found (are you missing a using directive or an assembly reference?)
“ IApplicationBuilder”不包含“ UseSession”的定义,找不到可以接受类型为“ IApplicationBuilder”的第一个参数的扩展方法“ UseSession”(您是否缺少using指令或程序集引用?)
I tried installing ASPNETCore.Session
package from NuGet but couldn't. 我尝试从NuGet安装
ASPNETCore.Session
程序包,但无法。
Can anyone help me finding the root cause of the issue? 谁能帮助我找到问题的根本原因?
First inject Session Service into your ConfigureServices
method: 首先将会话服务注入您的
ConfigureServices
方法:
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromSeconds(2400);
options.Cookie.HttpOnly = true;
});
then use app.UseSession();
然后使用
app.UseSession();
in Configure
Method. 在
Configure
方法中。
In ASP.NET Core Session doesn't support Generic data type you'll need to add this extension 在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);
}
}
and to use it: 并使用它:
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.