Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migrating global.asax to ASP.NET 5

Few days ago .NET Core RC1 got released and I gave it a go for the first time after reading a lot about it, I like it but its a bit different. I am trying to migrate a small blog (built in MVC5) to MVC 6 & .NET Core. It wasn't hard but I am really struggling to recreate the exact same global.asax settings I had in MVC 5, ASP.NET 5 no longer has global.asax so I am unable to figure out what the replacement for most of the settings are?

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

PLEASE, is there a way to get the above code to work in MVC 6 without leaving any of the settings? This is a deal breaker for me, THANK YOU.

like image 569
Cindro Avatar asked Nov 23 '15 11:11

Cindro


3 Answers

Even being an old question I'll put this as I've seen that no one gives a lead how to migrate global.asax methods to Startup.cs In the Configure section of Startup file, you just need to add

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

That's not a working solution, this is just to show how to work with middleware and applying logic for each request.

Hope it helps.

like image 86
Elmer Dantas Avatar answered Oct 18 '22 16:10

Elmer Dantas


To replace Application_Start, put your initialisation code in your Startup class.

Application_BeginRequest, Application_EndRequest, Application_AuthenticateRequest and Application_Error can be replaced by a middleware (global.asax is an HTTP Module which were replace by middleware)

Regarding Application_AuthenticateRequest, you should also read the doc about Request features

like image 4
agua from mars Avatar answered Oct 18 '22 14:10

agua from mars


According to this blogpost from Shawn Wildermuth and also he had webinar on Pluralsight about a week ago, where he told that MVC 5 global.asax, packages.config, and web.config are gone in ASP 5. So in the ASP 5 all configuration from former MVC 5 global.asax goes into new root Startup.cs file.

like image 2
user2771704 Avatar answered Oct 18 '22 16:10

user2771704