DISCLAIMER - this is specifically for handling 404s with static files. If you want to serve an Umbraco page see the docs, or use the package mentionned above.
Found my code, I remember now...
Depending on what you want to serve 404s for, you may only need to do this in one place or two.
If you need to serve custom 404s for non-umbraco paths - e.g. /somefile.txt, /somefile.html etc. the simplest way I've found is to use the built in UseStatusCodePagesWithReExecute middleware like this:
csharp
//program.cs
//...
app.UseStatusCodePagesWithReExecute("/Errors/{0}.html");
app.UseUmbraco()
//...
Then just pop a static file at
~/wwwroot/Errors/404.html
.
For Umbraco, the simplest thing to do is to override the view that Umbraco uses for it's default 404s.
Add a new file at
~/umbraco/UmbracoWebsite/NotFound.cshtml
, this will overwrite the default one that ships with Umbraco (and will get called by Umbraco's built in middleware)
You can combine the two approaches like so with a
NotFound.cshtml
that's a bit like this:
csharp
@using Umbraco.Extensions
@using Microsoft.AspNetCore.Hosting
@inject IWebHostEnvironment host
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<cache>
@Html.Raw(await System.IO.File.ReadAllTextAsync(host.MapPathWebRoot("/Errors/404.html")))
</cache>