How to enable sessions in C# ASP.NET Core?

WBOY
Release: 2023-09-07 08:41:05
forward
602 people have browsed it

如何在 C# ASP.NET Core 中启用会话?

Session is a feature in ASP.NET Core that enables us to save/store user data.

Session stores data in a dictionary on the server, using SessionId as the key.

The SessionId is stored in the client's cookie. The SessionId cookie is sent via per request.

SessionId cookie is specific to each browser and cannot be shared between different browsers.

SessionId cookie does not specify a timeout and will be deleted when the browser is closed The browser session ends.

On the server side, sessions are retained for a limited time. The default session timeout is Server is 20 minutes, but can be configured.

Microsoft.AspNetCore.Session package provides middleware for managing sessions in ASP.NET Core. To use sessions in our application, we need to add this package as a dependency of the project in the project.json file.

The next step is to configure the session in the Startup class.

We need to call the "AddSession" method in the ConfigureServices method of the startup class.

The "AddSession" method has an overloaded method that accepts various session parameters

Options, such as idle timeout, cookie name and cookie domain, etc.

If we don't pass session options, the system will take the default options.

Example

public class Startup {
   public void Configure(IApplicationBuilder app){
      app.UseSession();
      app.UseMvc();
      app.Run(context => {
         return context.Response.WriteAsync("Hello World!");
      });
   }
   public void ConfigureServices(IServiceCollection services){
      services.AddMvc();
      services.AddSession(options => {
         options.IdleTimeout = TimeSpan.FromMinutes(60);
      });
   }
}
Copy after login

How to access the session

public class HomeController : Controller{
   [Route("home/index")]
   public IActionResult Index(){
      HttpContext.Session.SetString("product","laptop");
      return View();
   }
   [Route("home/GetSessionData")]
   public IActionResult GetSessionData(){
      ViewBag.data = HttpContext.Session.GetString("product");;
      return View();
   }
}
Copy after login

The above is the detailed content of How to enable sessions in C# ASP.NET Core?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!