Custom error page for Http error 404.13 ASP.NET Core MVC

后端 未结 2 1264
广开言路
广开言路 2021-01-05 07:42

I am fairly new to ASP.NET and MVC in general; I have been migrating an ASP.NET MVC app to ASP.NET MVC Core. In the former framework I was able to handle an HttpException fo

2条回答
  •  迷失自我
    2021-01-05 08:06

    Old post, but still relevant. My Core 2.2 MVC project, which include large streaming file uploads, needed a graceful handling of a 404.13 (request size too large) result. The usual way of setting up status code handling (graceful views) is in Startup.cs Configure() plus an action method to match:

    app.UseStatusCodePagesWithReExecute("/Error/Error", "?statusCode={0}");
    

    and

    public IActionResult Error(int? statusCode = null)
    {
        if (statusCode.HasValue)
        {
            Log.Error($"Error statusCode: {statusCode}");
            if (statusCode == 403)
            {
                return View(nameof(AccessDenied));
            }
            if (statusCode == 404)
            {
                return View(nameof(PageNotFound));
            }
        }
    
        return View(new ErrorViewModel 
            {
                RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier 
            });
    }
    

    But because a 404.13 error is handled by IIS, not in the MVC pipeline, the code above did not allow establishing a graceful 'upload too large' error view. To do that, I had to hold my nose and add the following web.config to my Core 2.2 project. Note that removing the 404.13 also removed 404, so the ErrorController() code no longer handled 404s, hence the two custom error handlers below. Hope this helps someone!

    
    
      
        
          
            
            
          
        
        
          
          
          
          
        
      
    
    

提交回复
热议问题