Search code examples
c#asp.net-core-webapisession-variables.net-7.0

How do you access HttpContext.Session in an ASP.NET Core 7 Web API?


I've created an ASP.NET Core 7 Web API, and I need to store some values in session memory, but I am getting this exception:

Unable to resolve service for type 'Microsoft.AspNetCore.DataProtection.IDataProtectionProvider' while attempting to activate 'Microsoft.AspNetCore.Session.SessionMiddleware'.

Program.cs - based on the documentation I could find the addition of the 2 indicated lines of code should work.

internal class Program
{
    private static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // Add services to the container.

        builder.Services.AddControllers();
        // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
        builder.Services.AddEndpointsApiExplorer();
        builder.Services.AddSwaggerGen();
        
        //added to access session
        builder.Services.AddDistributedMemoryCache();

        var app = builder.Build();

        // Configure the HTTP request pipeline.
        if (app.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI();
        }

        app.UseHttpsRedirection();

        app.UseAuthorization();

        //added to access session
        app.UseSession();

        app.MapControllers();

        app.Run();
    }
}

Solution

  • I tried many different ways to be able to use session variables but continued to get exceptions so I switched to memory cache. Program.Main

    private static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
    
        // Add services to the container.
    
        builder.Services.AddControllers();
        builder.Services.AddEndpointsApiExplorer();
        builder.Services.AddSwaggerGen();
        builder.Services.AddMemoryCache();  //Added this service
        var app = builder.Build();
    
        // Configure the HTTP request pipeline.
        if (app.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI();
        }
    
        app.UseHttpsRedirection();
    
        app.UseAuthorization();
    
        app.MapControllers();
    
        app.Run();
    }
    

    Controller

    [Route("api/[controller]")]
    [ApiController]
    public class DatabaseController : ControllerBase
    {
        private Database? _database = null;
        private IMemoryCache _memoryCache;
    
        public DatabaseController(IMemoryCache memoryCache)
        {
            _memoryCache = memoryCache;
    
            try
            {
                _database = _memoryCache.Get<Database>("database");
                if (_database == null)
                {
                    SmDbActions smDbActions = new SmDbActions();
                    DataAccess.ActionResult actionResult = smDbActions.LoadDatabase();
                    if (!actionResult.Success) { throw actionResult.Exception; }
                    _database = (Database?)actionResult.Result;
                    _memoryCache.Set("database", _database);
                }
            }
            catch (Exception ex)
            {
                Log.LogEvent(new LogItem(ex.ToString()));
    
                throw;
            }
        }
    }