Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does ASP.NET Core handle 404 errors?

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "how to deal with 404 errors in ASP.NET Core". In daily operation, I believe many people have doubts about how to deal with 404 errors in ASP.NET Core. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to deal with 404 errors by ASP.NET Core". Next, please follow the editor to study!

When the web page is not found and the application returns a 404 error, ASP.NET Core MVC only renders the generic browser error page, as shown in the following figure

It's not very elegant, is it? The 404 pages we usually see usually look like this.

There's something like this.

I tried JD.com. If the address does not exist, it will be redirected to the home page.

Let's demonstrate how to implement this custom 404 page processing in ASP.NET Core.

New project ASP.NET Core MVC (WebApi is also handled in the same way)

The effect of running a new project directly.

Enter an address / test404 at random

When the web page is not found and the application returns a 404 error, ASP.NET Core MVC only renders the generic browser error page, as shown in the following figure

Mode one

FallbackEndpointRouteBuilderExtensions.MapFallback

What is this?

It probably means that this is registering a wildcard route with the lowest priority to match all routes, so let's try the effect.

/ / Program.csapp.UseAuthorization (); app.MapControllerRoute (name: "default", pattern: "{controller=Home} / {action=Index} / {id?}"); app.MapFallback (async (ctx) = > {ctx.Response.Body.Write (Encoding.UTF8.GetBytes ("404 from Fallback");}); app.Run ()

The effect of trying is as follows

Mode 2 Custom wildcard routing

Add an Action to HomeController as follows

/ / HomeController.cs [Route ("{* url}", Order = 9999)] public IActionResult Page404 () {return View ();}

Add the corresponding View page as follows

/ / Page404.cshtml@ {ViewData ["Title"] = "404";} 404 for {* url}

Although the above two methods can handle 404 error pages normally, 404 errors thrown within the program cannot be intercepted.

Add a test Action as follows

[Route ("/ test404")] public IActionResult test404 () {/ / some business processing, and finally return 404 / / return NotFound (); return StatusCode (404);}

You see, in this 404 scenario, the above methods failed to intercept.

Mode 3

Custom Middleware intercept

The code is as follows, and there is no introduction here on how to use Middleware

App.Use ((context, next) = > {var res = next (context); if (context.Response.StatusCode = = 404) {context.Response.StatusCode = 200; context.Response.Body.Write (Encoding.UTF8.GetBytes ("404 from Middleware"));} return res;})

Comment out the code of mode one and mode two, and run the test as follows

Address that does not exist

Address that exists, but business returns 404

Mode 4

UseStatusCodePagesWithReExecute

Comment on the code of the previous method

App.UseStatusCodePagesWithReExecute ("/ error/ {0}"); / / HomeController.cs [Route ("test401")] public IActionResult test401 () {return StatusCode (401);} public class ErrorController: Controller {[Route ("error/404", Order = 9)] public IActionResult Error404 () {ViewBag.code = 404; return View () } [Route ("error/ {code:int}", Order = 1)] public IActionResult Error (int code) {ViewBag.code = code; switch (code) {case 404: ViewBag.msg = "Sorry, the requested resource does not exist." ; break; case 401: ViewBag.msg = "Sorry, you do not have permission to access this page." ; break; default: ViewBag.msg = "Service exception, please try again later!" ; break;} return View ("Error404");}} / / Error404.cshtml@ {} @ ViewBag.code: @ ViewBag.msg

Test effect

Mode 5 configure ASP.NET pipeline in web.config node to handle 404 error

This is the iis configuration in the previous framwork era, and it is no longer recommended or tested.

At this point, the study on "how to deal with ASP.NET Core errors" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report