AspNet Core 2 No service for HttpContext sessions issue

May 10 2018 10:48 AM
Error:
AspNet Core 2 No service for type 'Microsoft.AspNetCore.Http.HttpContext'
 
im using https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.1&tabs=aspnetcore2x as guide, but seems to be not enough.
 
in Startup.cs
  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3. services.AddDistributedMemoryCache();  
  4. services.AddMvc().AddSessionStateTempDataProvider();  
  5. services.AddSession(options =>  
  6. {  
  7. // Set a short timeout for easy testing.  
  8. options.IdleTimeout = TimeSpan.FromMinutes(1);  
  9. options.Cookie.HttpOnly = true;  
  10. });//<<==  
  11. }  
  12. public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  13. {  
  14. if (env.IsDevelopment())  
  15. {  
  16. app.UseDeveloperExceptionPage();  
  17. app.UseBrowserLink();  
  18. }  
  19. else  
  20. {  
  21. app.UseExceptionHandler("/Home/Error");  
  22. }  
  23. app.UseStaticFiles();  
  24. app.UseSession();//<<==  
  25. app.UseMvc(routes =>  
  26. {  
  27. routes.MapRoute(  
  28. name: "default",  
  29. template: "{controller=Home}/{action=Index}/{id?}");  
  30. routes.MapSpaFallbackRoute(  
  31. name: "spa-fallback",  
  32. defaults: new { controller = "Home", action = "Index" });  
  33. });  
  34. }  
in home controller:
  1. using Microsoft.AspNetCore.Http;  
  2. HttpContext.Session.SetString("TestName", user.UserName);  
  3. HttpContext.Session.SetString("TestVal", user.testVal.ToString());  
to this point it seems to be working, im able to navigate through different pages and i can use/check sessions in controller side.
 
But the problem is when im trying to use sessions in any view
 
View side:
  1. @using Microsoft.AspNetCore.Http  
  2. @inject HttpContext HttpContext  
  3. @if (@HttpContext.Session.GetString("testVal").Equals("True"))  
  4. {  
  5. <td><input type="checkbox"></td>  
  6. }  
  7. else  
  8. {  
  9. <td><input type="checkbox" readonly></td>  
  10. }  
when i try to get or set sessions cshtml/view side i get the error
 
can you please help?

Answers (1)