If you have a standard ASP.NET 5 Web application template project you can get a really nice solution that will handle both keeping the error status code at the same time as you serve the cshtml file of your choice.
Startup.cs, in the Configure method
Replace
app.UseExceptionHandler("/Error");
with
app.UseStatusCodePagesWithReExecute("/Home/Errors/{0}");
Then remove the following catchall:
app.Run(async (context) =>
{
var logger = loggerFactory.CreateLogger("Catchall Endpoint");
logger.LogInformation("No endpoint found for request {path}", context.Request.Path);
await context.Response.WriteAsync("No endpoint found - try /api/todo.");
});
In HomeController.cs
Replace the current Error method with the following one:
public IActionResult Errors(string id)
{
if (id == "500" | id == "404")
{
return View($"~/Views/Home/Error/{id}.cshtml");
}
return View("~/Views/Shared/Error.cshtml");
}
That way you can add error files you feel the users can benefit from (while search engines and such still get the right status codes)
Now add a folder named Error in ~Views/Home folder
Create two .cshtml files. Name the first one 404.cshtml and the second one 500.cshtml.
Give them some useful content and the start the application and write something like http://localhost:44306/idonthaveanendpointhere and confirm the setup works.
Also press F12 developer tools and confirm the status code is 404.