将global.asax迁移到ASP.NET 5

几天前.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中工作而不留下任何设置? 谢谢你,这对我来说是一个交易破坏者。

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

Application_BeginRequestApplication_EndRequestApplication_AuthenticateRequestApplication_Error可以被中间件替换( global.asax是一个被middleware取代的HTTP Module

关于Application_AuthenticateRequest ,您还应该阅读有关请求function的文档

根据Shawn Wildermuth撰写的这篇博文,大约一周前他在Pluralsight上进行了网络研讨会,他告诉我, ASP 5中的MVC 5 global.asax,packages.config和web.config已经消失了。 所以在ASP 5 ,前MVC 5 global.asax的所有配置都进入新的根Startup.cs文件。

即使是一个老问题,我也会这样,因为我已经看到没有人能够如何将global.asax方法迁移到Startup.cs在Startup文件的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. }); 

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

希望能帮助到你。