ASP.NET Zero Session Management

2.3k views Asked by At

I am completely new to ASP.NET Core and DDD (domain-driven design). I recently purchased the ASP.NET Zero startup template to ease the pain and learning curve of getting started. I love the project, but I am having difficulty with session state.

I use third-party components in our application, like the Neodynamic products.

I need a way to pass the current session ID and protocol to several of these components from their respective controllers. In ASP.NET MVC, it was relatively easy with HttpContext.Session.Id and HttpContext.Request.Scheme. This seems to be a bit more confusing in ASP.NET Core.

Can someone get me started?

2

There are 2 answers

0
aaron On BEST ANSWER

The Microsoft.AspNetCore.Session package provides middleware for managing session state.

Call AddSession() and UseSession() in your Startup class:

public class Startup
{
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        // Adds a default in-memory implementation of IDistributedCache.
        services.AddDistributedMemoryCache();

        services.AddSession();

        // ...
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // ...

        app.UseSession();

        app.UseMvc(...);
    }
}

Reference: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state

1
Vivek Nuna On

UserManager class gives you the current user's info.

Example:

 public async Task<string> GetCurrentUserName()
 {
      var user = await UserManager.FindByIdAsync(AbpSession.GetUserId().ToString());
      return user.UserName;
 }

IAbpSession AbpSession can also give you useful info which you use by inheriting from ApplicationService abstract class. Interface IAbpSession is defined in Abp.dll.

Inject IAbpSession and UserManager in the required class wherever you want to get info.

public class TestClass
{
    private readonly IAbpSession _abpSession;
    private readonly UserManager _userManager;

    public TestClass(
        IAbpSession abpSession,
        UserManager userManager)
    {
        _abpSession = abpSession;
        _userManager = userManager;
    }
}