Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using UseStatusCodePagesWithReExecute, statuscode is not sent to browser

Tags:

asp.net-core

I have a simple .NET Core 2.0 project. Here is the Configure method:

public void Configure(IApplicationBuilder app, IHostingEnvironment environment)
{
  app.UseStatusCodePagesWithReExecute("/error/{0}.html");

  app.UseStaticFiles();

  app.UseMvc(routes =>
  {
    routes.MapRoute(
      name: "default",
      template: "{controller}/{action?}/{id?}",
      defaults: new { controller = "Home", action = "Index" });
    });
  }

When I enter an invalid url, /error/404.html is displayed as expected, but the browser gets a 200 status code, instead of the expected 404 status.

What am I doing wrong? Can I not use a static html file as error page?

like image 657
Bjarte Aune Olsen Avatar asked Sep 22 '17 21:09

Bjarte Aune Olsen


1 Answers

When you use app.UseStatusCodePagesWithReExecuteyou

Adds a StatusCodePages middleware that specifies that the response body should be generated by re-executing the request pipeline using alternate path.

As path /error/404.html exists and works OK, the 200 status is used.


You may use the following approach (look into this article for more detailed explanation):

setup action that will return View based on a status code, passed as a query parameter

public class ErrorController : Controller  
{
    [HttpGet("/error")]
    public IActionResult Error(int? statusCode = null)
    {
        if (statusCode.HasValue)
        {
            // here is the trick
            this.HttpContext.Response.StatusCode = statusCode.Value;
        }

        //return a static file. 
        return File("~/error/${statusCode}.html", "text/html");

        // or return View 
        // return View(<view name based on statusCode>);
    }
}

then register middleware as

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

this placeholder {0} will be replaced with the status code integer automatically during redirect.

like image 52
Set Avatar answered Nov 02 '22 16:11

Set