Search code examples
c#asp.net-coreasp.net-core-mvc

Alternative to 'Session_Start' in MVC 6


I'am trying to rewrite an old e-shop to MVC 6, and I'am solving a lot of problems. One of it is that I need to set up some default data when session is beginning. I found nothing usable for thins in MVC 6. I have multiple shops implemented as one application, and I need to set for example a ShopID when session is starting. Setting is by IP address. This is not the only thing I'am setting there, but its one of the most descriptive things.

Do you have some idea how to implement this, or advice how to do it in different way ?

Sample code from old implementation in global.asax:

void Session_Start(object sender, EventArgs e) 
{
    string url = Request.Url.Host;
    switch (url)
    {
        case "127.0.0.207":
            (SomeSessionObject)Session["SessionData"].ShopID = 123;
            break;
        case "127.0.0.210":
            (SomeSessionObject)Session["SessionData"].ShopID = 345;
            break;
    }
}

This code i would like to write down somehow in MVC 6, but have no idea where to place it, or even if it is possible.


Solution

  • Following is probably one way of achieving what you are trying to do...Here I am registering a middleware right after the Session middleware so that when a request comes in it would be intercepted by this middleware after Session middleware does its work. You can try it and see if it suits your scenario.

    using Microsoft.AspNet.Builder;
    using Microsoft.AspNet.Hosting;
    using Microsoft.AspNet.Http;
    using Microsoft.Framework.DependencyInjection;
    
    namespace WebApplication43
    {
        public class Startup
        {
            // This method gets called by a runtime.
            // Use this method to add services to the container
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddCaching();
    
                services.AddSession();
    
                services.AddMvc();
            }
    
            // Configure is called after ConfigureServices is called.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                app.UseStaticFiles();
    
                app.UseSession();
    
                app.Use((httpContext, nextMiddleware) =>
                {
                    httpContext.Session.SetInt32("key1", 10);
                    httpContext.Session.SetString("key2", "blah");
    
                    return nextMiddleware();
                });
    
                app.UseMvc();
            }
        }
    }
    

    Related package dependencies in project.json:

    "dependencies": {
        "Microsoft.AspNet.Mvc": "6.0.0-beta7",
        "Microsoft.AspNet.StaticFiles": "1.0.0-beta7",
        "Microsoft.AspNet.Session": "1.0.0-beta7",
        "Microsoft.Framework.Caching.Memory": "1.0.0-beta7",
        "Microsoft.AspNet.Http.Extensions": "1.0.0-beta7",