如何创建和访问Session .net core api? [英] How to Create and Access Session .net core api?
问题描述
我需要在 api 中创建和访问会话.例如,我有一个名为 Login、Profile 的 api.当当时调用登录 api 时,我需要创建会话,并且需要访问配置文件 api 中的会话.清除会话后,登录名和配置文件 api 不允许用户访问.怎么做.
I need to create and access session in api. For example i have api called Login,Profile. When the login api is called at that time i need to create session and i need to access the session in profile api. When the session is cleared the login and profile api don't allow the user to access. How to do it.
谢谢..
推荐答案
其实.net core 可以轻松访问 session.会话机制是aspnet(.netcore 也是如此)的一个基本特性https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2
Actually .net core can access session easily. Session mechanism is a basic feature in aspnet (.netcore as well) https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2
我认为你只需要添加
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
});
在ConfigureServices
和:
app.UseSession();
在配置
然后你可以通过在你需要的地方注入 ISession
来在任何地方使用它.由于这是按设计分发的,您应该使用诸如 JsonConvert.SerializeObject
之类的东西序列化您的数据,然后将它们反序列化.
Then you can use it anywhere by injecting ISession
where you need. As this is distributed by design you should serialize your data using something like JsonConvert.SerializeObject
and deserialize them back.
此处描述的此功能与安全概念无关.
This feature described here has nothing with security concepts.
这篇关于如何创建和访问Session .net core api?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!