Reputation: 3310
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?
Upvotes: 8
Views: 14559
Reputation: 49779
When you use app.UseStatusCodePagesWithReExecute
you
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.
Upvotes: 14