Unable to access asp.net core session

Hi, please help me try test sessions in the asp.net core, but when I establish a session and get it from another controller, it looks like null

heres my launch

public class Startup { public IConfigurationRoot Configuration { get; } public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); // Adds a default in-memory implementation of IDistributedCache. services.AddDistributedMemoryCache(); services.AddSession(options => { // Set a short timeout for easy testing. options.IdleTimeout = TimeSpan.FromSeconds(600); options.CookieHttpOnly = true; }); services.AddSingleton<IConfiguration>(Configuration); services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>(); services.AddTransient<IApiHelper, ApiHelper>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseSession(); app.UseDeveloperExceptionPage(); if (env.IsDevelopment()) { app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions { HotModuleReplacement = true, ReactHotModuleReplacement = true }); } //var connectionString = Configuration.GetSection("ConnectionStrings").GetSection("ClientConnection").Value; app.UseStaticFiles(); loggerFactory.AddConsole(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); routes.MapSpaFallbackRoute( name: "spa-fallback", defaults: new { controller = "Home", action = "Index" }); }); } public static void Main(string[] args) { var host = new WebHostBuilder() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseKestrel() .UseStartup<Startup>() .Build(); host.Run(); } } 

and this is how I set up the session

 public class HomeController : Controller { public IActionResult Index() { HttpContext.Session.SetString("Test", "Ben Rules!"); return View(); } public IActionResult Error() { return View(); } } 

and here is my sample code to get the session again, but it looks like null

  [HttpGet("[action]")] public IEnumerable<JobDescription> GetJobDefinitions() { //this is always null var xd = HttpContext.Session.GetString("Test"); var x = _apiHelper.SendRequest<Boolean>($"api/JobRequest/GetJobRequest",null); var returnValue = new List<JobDescription>(); returnValue = jobDescriptionManager.GetJobDescriptions(); return returnValue; } 

thanks for the help

+6
source share
3 answers

To access the session, you will want to use HttpContext.Current to indicate the desired session. However, a more suitable approach would be:

 public interface MemoryStorageService<T> where T : class { IEnumerable<T> Get(); } public class ExampleService : MemoryStorageService<Example> { private IExampleFactory factory; public ExampleService(IExampleFactory factory) { this.factory = factory; } public IEnumerable<Example> Get() { using(var context = factory.CreateExampleRepository()) return context.GetExamples(); } } 

Then, inside your dependency injection or inside Core, your IServiceCollection just add services.AddCaching(); . This will add the MemoryCache to your application.

 public class SampleController : Controller { private readonly IMemoryCache cache; private readonly IMemoryStorageService<Example> service; public SampleController(IMemoryCache cache, IMemoryStorageService<Example> service) { this.cache = cache; this.service = service; } private List<Employee> SetGetMemoryCache() { string key = "MyMemoryKey-Cache"; List<Example> examples; if (!cache.TryGetValue(key, out examples)) { examples = service.Get().ToList(); cache.Set(key, examples, new MemoryCacheEntryOptions() .SetAbsoluteExpiration(TimeSpan.FromMinutes(1))); } else { examples = cache.Get(key) as List<Example>; } return examples; } } 
0
source

For VS2017 follow this official MSDN article regarding Session and Application Status in ASP.NET Core . You can test your script in the following example that I created. Note Although the code below looks long, you are actually only making minor changes to the default application, which is created from the main ASP.NET template template. Just follow these steps:

  • Build an ASP.NET Core MVC Application Using the VS2017 Default VS2017

  • Change the default value of the Home controller as shown below

  • Make sure the Startup.cs file has session related entries, as shown in the Startup.cs file below

  • Launch the application and click the Home link on the top panel. This will store the session values โ€‹โ€‹shown below ( Nam Wam , 2017 and current date )

  • Click the About link on the top panel. You will notice that session values โ€‹โ€‹have been passed to the About controller. But I know that was not your question, since this is only a test of passing a session of value for another action on the same controller. So, to answer your question, follow the next 3 steps.

  • Create another AnotherController controller - as shown below - with the new Test() action and View Test.cshtml inside the Views\Test folder

  • In _Layout.cshtml add another link <li><a asp-area="" asp-controller="Another" asp-action="Test">Test View</a></li> right after <li>...Contact...</li> as shown below

  • Launch the application again and first click the Home link at the top of the bar. Then click the Test link in the top pane. You will notice that the session values โ€‹โ€‹were passed from HomController to AnotherController and were successfully displayed in the Test view.

Homecontroller

 using System; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; namespace MyProject.Controllers { public class HomeController : Controller { const string SessionKeyName = "_Name"; const string SessionKeyFY = "_FY"; const string SessionKeyDate = "_Date"; public IActionResult Index() { HttpContext.Session.SetString(SessionKeyName, "Nam Wam"); HttpContext.Session.SetInt32(SessionKeyFY , 2017); // Requires you add the Set extension method mentioned in the SessionExtensions static class. HttpContext.Session.Set<DateTime>(SessionKeyDate, DateTime.Now); return View(); } public IActionResult About() { ViewBag.Name = HttpContext.Session.GetString(SessionKeyName); ViewBag.FY = HttpContext.Session.GetInt32(SessionKeyFY); ViewBag.Date = HttpContext.Session.Get<DateTime>(SessionKeyDate); ViewData["Message"] = "Session State In Asp.Net Core 1.1"; return View(); } public IActionResult Contact() { ViewData["Message"] = "Contact Details"; return View(); } public IActionResult Error() { return View(); } } 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); } } } 

About.cshtml [Displaying session variable values โ€‹โ€‹from the same controller]

 @{ ViewData["Title"] = "ASP.Net Core !!"; } <h2>@ViewData["Title"].</h2> <h3>@ViewData["Message"]</h3> <table class="table table-responsive"> <tr> <th>Name</th> <th>Fiscal Year</th> </tr> <tr> <td>@ViewBag.Name</td> <td>@ViewBag.FY</td> </tr> </table> <label>Date : @(ViewBag.Date.ToString("dd/MM/yyyy") != "01/01/0001" ? ViewBag.Date.ToString("dd/MM/yyyy") : "")</label> 

AnotherController . [Other controller than HomeController]:

 using System; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; public class AnotherController : Controller { const string SessionKeyName = "_Name"; const string SessionKeyFY = "_FY"; const string SessionKeyDate = "_Date"; // GET: /<controller>/ public IActionResult Test() { ViewBag.Name = HttpContext.Session.GetString(SessionKeyName); ViewBag.FY = HttpContext.Session.GetInt32(SessionKeyFY); ViewBag.Date = HttpContext.Session.Get<DateTime>(SessionKeyDate); ViewData["Message"] = "Session State passed to different controller"; return View(); } } 

Test.cshtml : [Mapping session variable values โ€‹โ€‹passed from the Home controller to Another controller]

 @{ ViewData["Title"] = "View sent from AnotherController"; } <h2>@ViewData["Title"].</h2> <h3>@ViewData["Message"]</h3> <table class="table table-responsive"> <tr> <th>Test-Name</th> <th>Test-FY</th> </tr> <tr> <td>@ViewBag.Name</td> <td>@ViewBag.FY</td> </tr> </table> <label>Date : @(ViewBag.Date.ToString("dd/MM/yyyy") != "01/01/0001" ? ViewBag.Date.ToString("dd/MM/yyyy") : "")</label> 

_Layout.cshtml

 .... <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li> <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li> <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li> <li><a asp-area="" asp-controller="Another" asp-action="Test">Test View</a></li> </ul> </div> .... 

Startup.cs : [Make sure it includes some session-related entries. Most likely, when you created the ASP.NET Core MVC application in VS2017, these entries will already be there. But just make sure.]

 .... // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //In-Memory services.AddDistributedMemoryCache(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(1);//Session Timeout. }); // Add framework services. services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseSession(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } .... 
0
source

To use Session in an MVC application, you need to: Install the NuGet package for Microsoft.AspNetCore.Session .

In Startup.cs ConfigureServices add AddSession() :

 services.AddMvc(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromHours(1); }); 

In Startup.cs configure add UseSession() :

 app.UseSession(); app.UseMvc(); 

And now you can use it in the controller:

Set up session

 string token="xx"; HttpContext.Session.SetString("UserToken", token); 

Get saved value

 var token = HttpContext.Session.GetString("UserToken"); 

In addition, ASP.NET Core 2. 1+ introduced some additional extension points, such as a cookie consent dialog. Therefore, we require consent to the storage of cookies from the user.

If you click Accept on the privacy banner, then ASP.NET Core will be able to record session cookies.

0
source

Source: https://habr.com/ru/post/1268106/


All Articles