這篇文章給大家介紹Session怎么在Asp.net Core項目中使用,內(nèi)容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

添加Session
在你的項目上基于NuGet添加:Microsoft.AspNetCore.Session。
修改startup.cs
在startup.cs找到方法ConfigureServices(IServiceCollection services) 注入Session(這個地方是Asp.net Core pipeline):services.AddSession();
接下來我們要告訴Asp.net Core使用內(nèi)存存儲Session數(shù)據(jù),在Configure(IApplicationBuilder app,...)中添加代碼:app.UserSession();
Session
1、在MVC Controller里使用HttpContext.Session
using Microsoft.AspNetCore.Http;
public class HomeController:Controller
{
public IActionResult Index()
{
HttpContext.Session.SetString("code","123456");
return View();
}
public IActionResult About()
{
ViewBag.Code=HttpContext.Session.GetString("code");
return View();
}
}2、如果不是在Controller里,你可以注入IHttpContextAccessor
public class SomeOtherClass
{
private readonly IHttpContextAccessor _httpContextAccessor;
private ISession _session=> _httpContextAccessor.HttpContext.Session;
public SomeOtherClass(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor=httpContextAccessor;
}
public void Set()
{
_session.SetString("code","123456");
}
public void Get()
{
string code = _session.GetString("code");
}
}存儲復(fù)雜對象
存儲對象時把對象序列化成一個json字符串存儲。
public static class SessionExtensions
{
public static void SetObjectAsJson(this ISession session, string key, object value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T GetObjectFromJson<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
}
}var myComplexObject = new MyClass();
HttpContext.Session.SetObjectAsJson("Test", myComplexObject);
var myComplexObject = HttpContext.Session.GetObjectFromJson<MyClass>("Test");使用SQL Server或Redis存儲
1、SQL Server
添加引用 "Microsoft.Extensions.Caching.SqlServer": "1.0.0"
注入:
// Microsoft SQL Server implementation of IDistributedCache.
// Note that this would require setting up the session state database.
services.AddSqlServerCache(o =>
{
o.ConnectionString = "Server=.;Database=ASPNET5SessionState;Trusted_Connection=True;";
o.SchemaName = "dbo";
o.TableName = "Sessions";
});2、Redis
添加引用 "Microsoft.Extensions.Caching.Redis": "1.0.0"
注入:
// Redis implementation of IDistributedCache. // This will override any previously registered IDistributedCache service. services.AddSingleton<IDistributedCache, RedisCache>();
關(guān)于Session怎么在Asp.net Core項目中使用就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
當前標題:Session怎么在Asp.netCore項目中使用-創(chuàng)新互聯(lián)
新聞來源:http://www.chinadenli.net/article26/dehgjg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、云服務(wù)器、網(wǎng)站維護、營銷型網(wǎng)站建設(shè)、微信公眾號、用戶體驗
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)