几天前.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中运行?这对我来说是个大难题,谢谢。
最佳答案
甚至是一个老问题,我都会提出这一点,因为我发现没人能带头介绍如何将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.
});
那不是一个可行的解决方案,这只是说明如何使用中间件并为每个请求应用逻辑。
希望能帮助到你。
关于c# - 将global.asax迁移到ASP.NET 5,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33870518/