【问题标题】:Migrating global.asax to ASP.NET 5将 global.asax 迁移到 ASP.NET 5
【发布时间】:2016-02-25 12:40:50
【问题描述】:

几天前 .NET Core RC1 发布了,在阅读了很多关于它的内容后,我第一次尝试了它,我喜欢它,但它有点不同。我正在尝试将一个小型博客(内置于 MVC5)迁移到 MVC 6 和 .NET Core。这并不难,但我真的很难重新创建与 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 中工作而无需离开任何设置?这对我来说是一个交易破坏者,谢谢。

【问题讨论】:

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


【解决方案1】:

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

【讨论】:

  • 我明白,但我怎样才能成功地将以上所有代码移动到 Startup.cs?我只设法单独移动路由。
  • @Cindro 不幸的是,这不是一个简单的问题,因为事情发生了很大变化,所以我不知道,抱歉。例如捆绑几乎完全改变:见这篇文章jeffreyfritz.com/2015/05/…。从 MVC 5 中删除的许多东西也一样,比如 global.asax、packages.config 和 web.config。因此,您很可能需要用新代码替换大部分代码。
  • 我知道,希望解决方案/替代方式能尽快发布。顺便说一句,关于 ASP.NET 5 中的捆绑,您可以使用这个包来像 4.5 中一样捆绑:github.com/Shazwazza/Smidge
  • @Cindro 谢谢。我会试试的。
【解决方案2】:

要替换 Application_Start,请将初始化代码放入 Startup 类。

Application_BeginRequest、Application_EndRequest、Application_AuthenticateRequest 和 Application_Error 可以被 middleware 替换(global.asax 是 HTTP Module,被 middleware 替换)

关于Application_AuthenticateRequest,你也应该阅读关于Request features的文档

【讨论】:

  • 我明白这一点,但我找不到任何关于如何重新创建我需要的所有中间件的好的教程。我只是对 ASP.NET 团队做出如此大的改变而没有提供明确记录的替代方案感到沮丧。
  • 我相信他们会的。给他们时间。大家都忙着清理github上的问题。虽然它已准备好生产,但尚未发布第一个稳定版本。
  • @Cindro,doc 中有一个示例,还请检查 Request feature doc,这将有助于替换 Application_AuthenticateRequest
【解决方案3】:

即使是一个老问题,我也会提出这个问题,因为我已经看到没有人指导如何将 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.
                });

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

希望对你有帮助。

【讨论】:

  • 这段代码有点草率,但它确实捕获了所有请求。解决了我的问题,谢谢。
猜你喜欢
  • 2015-01-04
  • 2018-01-07
  • 1970-01-01
  • 2022-01-21
  • 2019-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-17
相关资源
最近更新 更多