How to handle 404 errors in ASP.NET Core MVC

ASP.Internet Core MVC is the .Internet Core counterpart of the ASP.Internet MVC framework for creating cross-platform, scalable, large-general performance internet programs and APIs making use of the Product-See-Controller style and design sample. Shockingly, while ASP.Internet Core gives a great deal of solutions for managing 404 faults gracefully, the ASP.Internet Core […]

ASP.Internet Core MVC is the .Internet Core counterpart of the ASP.Internet MVC framework for creating cross-platform, scalable, large-general performance internet programs and APIs making use of the Product-See-Controller style and design sample. Shockingly, while ASP.Internet Core gives a great deal of solutions for managing 404 faults gracefully, the ASP.Internet Core MVC runtime does not take benefit of them by default.

As a result, when a internet site is not found and a 404 mistake is returned by the software, ASP.Internet Core MVC presents only a generic browser mistake site (as demonstrated in Figure one beneath). This article discusses a few solutions in ASP.Internet Core we can use to manage 404 faults additional gracefully.

To function with the code illustrations provided in this article, you must have Visible Studio 2019 mounted in your program. If you do not previously have a copy, you can download Visible Studio 2019 listed here.

Build an ASP.Internet Core MVC venture

First off, let us produce an ASP.Internet Core venture in Visible Studio. Assuming Visible Studio 2019 is mounted in your program, adhere to the techniques outlined beneath to produce a new ASP.Internet Core venture in Visible Studio.

  1. Launch the Visible Studio IDE.
  2. Click on “Create new venture.”
  3. In the “Create new project” window, find “ASP.Internet Core Web Application” from the checklist of templates shown.
  4. Click Following. 
  5. In the “Configure your new project” window demonstrated upcoming, specify the identify and area for the new venture.
  6. Click Build.
  7. In the “Create a New ASP.Internet Core Web Application” window, find .Internet Core as the runtime and ASP.Internet Core three.one (or later) from the drop-down checklist at the top rated.
  8. Select “Web Application (Product-See-Controller)” as the venture template to produce a new ASP.Internet Core MVC software.
  9. Be certain that the check packing containers “Enable Docker Support” and “Configure for HTTPS” are unchecked as we will not be making use of those characteristics listed here.
  10. Be certain that Authentication is set to “No Authentication” as we will not be making use of authentication both.
  11. Click Build.

Adhering to these techniques will produce a new ASP.Internet Core MVC venture in Visible Studio 2019. We’ll use this venture to illustrate our 404 mistake managing solutions in the subsequent sections of this article.

When you execute the ASP.Internet Core MVC venture we have established in the previous portion, you will see the household site of the software alongside one another with the welcome message as demonstrated in Figure one beneath. 

aspnet core mvc 404 errors 01 IDG

Figure one: The default household site in ASP.Internet Core MVC. 

Now let us try to look through a internet site that does not exist. To do this, type http://localhost:6440/welcome in the tackle bar of your browser although the software is in execution. When the ASP.Internet Core MVC motor fails to identify the source for the specified URL, a 404 mistake will be returned and you will be introduced with the next mistake site. Which is not really classy, is it?

aspnet core mvc 404 errors 02 IDG

Figure two: The default 404 mistake site shown by ASP.Internet Core MVC for a non-existent internet site.

Verify Reaction.StatusCode in ASP.Internet Core MVC

There are various ways in which you can boost on this generic mistake site. A very simple remedy is to check for the HTTP position code 404 in the response. If found, you can redirect the management to a site that exists. The next code snippet illustrates how you can compose the required code in the Configure system of the Startup class to redirect to the household site if a 404 mistake has happened.

 app.Use(async (context, upcoming) =>
   
        await upcoming()
        if (context.Reaction.StatusCode == 404)
       
            context.Ask for.Path = "/Dwelling"
            await upcoming()
       
    )

Now if you execute the software and try to look through the URL http://localhost:6440/welcome, you will be redirected to the household site of the software.

The total code of the Configure system is provided beneath for your reference.

general public void Configure(IApplicationBuilder application, IWebHostEnvironment env)
       
            if (env.IsDevelopment())
           
                application.UseDeveloperExceptionPage()
           
            else
           
                application.UseExceptionHandler("/Dwelling/Mistake")
           
            application.Use(async (context, upcoming) =>
            
                await upcoming()
                if (context.Reaction.StatusCode == 404)
               
                    context.Ask for.Path = "/Dwelling"
                    await upcoming()
               
            )
            application.UseStaticFiles()
            application.UseRouting()
            application.UseAuthorization()
            application.UseEndpoints(endpoints =>
           
                endpoints.MapControllerRoute(
                    identify: "default",
                    pattern: "controller=Dwelling/action=Index/id?")
            )
       

Use UseStatusCodePages middleware in ASP.Internet Core MVC

A next remedy for managing 404 faults in ASP.Internet Core is by making use of the created-in UseStatusCodePages middleware. The next code snippet demonstrates how you can carry out StatusCodePages in the Configure system of the Startup class.

general public void Configure(IApplicationBuilder application, IWebHostEnvironment env)
       
            application.UseStatusCodePages()
            //Other code
       

Now when you execute the software and look through to the non-existent source, the output will be very similar to Figure three.

Copyright © 2020 IDG Communications, Inc.

Next Post

Meet ACE2, the Enzyme at the Center of the Covid-19 Mystery

All through the initial chaotic months of the Covid-19 pandemic, it was presently very clear that the novel coronavirus spreading about the globe did not affect everyone similarly. The earliest medical knowledge out of China confirmed that some people regularly fared worse than other individuals, notably guys, the elderly, and […]

Subscribe US Now