替代 MVC 6 中的 'Session_Start'

Alternative to 'Session_Start' in MVC 6

我正在尝试将一个旧的电子商店重写为 MVC 6,并且我正在解决很多问题。其中之一是我需要在会话开始时设置一些默认数据。我发现在 MVC 6 中没有任何东西可以用于 thins。 我有多个商店作为一个应用程序实现,我需要在会话开始时设置例如 ShopID。设置是通过 IP 地址。这不是我在那里设置的唯一东西,但它是最具描述性的东西之一。

您是否知道如何实现它,或者建议如何以不同的方式实现它?

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;
    }
    }

我想以某种方式在 MVC 6 中写下这段代码,但不知道将它放在哪里,即使可能也不知道。

以下可能是实现您正在尝试做的事情的一种方法...在这里,我在 Session 中间件之后立即注册一个中间件,这样当请求进入时,它会在 Session 中间件完成后被该中间件拦截是工作。你可以试试看是否适合你的场景。

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();
        }
    }
}

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",