将global.asax迁移到ASP.NET 5

时间:2015-11-23 11:54:59

标签: c# asp.net asp.net-mvc asp.net-core .net-core

几天前.NET Core RC1发布了,我在阅读了很多关于它之后第一次试了一下,我喜欢它,但它有点不同。我正在尝试将一个小博客(内置MVC5)迁移到MVC 6& .NET核心。这并不难,但我真的很难重新创建我在MVC 5中完全相同的global.asax设置,ASP.NET 5不再具有global.asax所以我无法弄清楚大多数的替换是什么设置是?

    protected void Application_Start()
    {
        ViewEngines.Engines.Clear();
        ViewEngines.Engines.Add(new RazorViewEngine());

        MvcHandler.DisableMvcResponseHeader = true;
        AntiForgeryConfig.SuppressXFrameOptionsHeader = true;

        BundleConfig.RegisterBundles(BundleTable.Bundles);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }

    protected void Application_BeginRequest()
    {
        Response.AddHeader("X-Frame-Options", "DENY");
    }

    protected void Application_EndRequest()
    {
        if (Response.StatusCode != 301 && Response.StatusCode != 302) return;

        var targetUrl = Response.RedirectLocation.Replace("ReturnUrl", "url");
        Response.RedirectLocation = targetUrl;
    }

    protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        string typeName;

        byte userType = (byte)(Context.Request.IsAuthenticated ? byte.Parse(User.Identity.Name.Split('|')[2]) : 1);

        switch (userType)
        {
            case 1: { typeName = "Client"; break; }
            case 2: { typeName = "Admin"; break; }
            default: { typeName = "Client"; break; }
        }

        var roles = new[] { typeName };

        if (Context.User != null)
        {
            Context.User = new GenericPrincipal(Context.User.Identity, roles);
        }
    }

    private void Application_Error(object sender, EventArgs e)
    {
        Exception ex = Server.GetLastError();

        if (ex is HttpAntiForgeryException)
        {
            Response.Clear();
            Server.ClearError();
            Response.Redirect("/error/cookie", true);
        }
    }

请问,有没有办法让上面的代码在MVC 6中工作而不留下任何设置?对我来说这是一个交易破坏者,谢谢。

2 个答案:

答案 0 :(得分:2)

来自this blogpost Shawn Wildermuth和他一周前在Pluralsight上进行过网络研讨会,在那里他告诉我MVC 5 global.asax,packages.config和web.config已经消失了ASP 5。因此,ASP 5来自MVC 5的所有配置global.asax都会进入新的根 Startup.cs 文件。

答案 1 :(得分:2)

即使是一个老问题,我也会这样做,因为我已经看到没有人能够指导如何将global.asax方法迁移到Startup.cs 在启动文件的Configure部分中,您只需添加

 app.Use(async (context, next) =>
                {       
                 //this will be call each request.
                 //Add headers      
                    context.Response.Headers.Add();
                 //check response status code
                  if(context.Response.StatusCode == 404) //do something
                 //check user
                 context.User.Identity.IsAuthenticated 
                //redirect
                 context.Request.Path = "some url"
                 await next() // will call next logic, in case here would be your controller.
                });

这不是一个有效的解决方案,这只是为了展示如何使用中间件并为每个请求应用逻辑。

希望它有所帮助。