Uploaded images not appearing in Blazor?
Are you getting 404 errors with images added via a file upload?
So I have only recent reconnected with Blazor following a fairly lengthy absence because I have a lot of clients where SEO is fairly critical and I didn’t believe at the time that Blazor could satisfy some of the shortcomings in this respect.
However, with the release of .Net 8 and static server side rendering I was prepared to give it another go, because I did actually enjoy the Blazor experience previously.
In January I switched over to using .Net 9 and starting building out the front end of one of my content managed websites, so that I could see how this was going to pan out and whether indeed it really would be able to deliver.
Everything was going pretty well, and I was deploying and testing in a shared hosting production environment as I was going, to make sure that everything was going to work as expected.
Then I hit a brick wall, as images included as part of the project were all rendering just fine, but anything added to the file system after that, be that via a file upload, ftp or any other means would not only not work but result in a 404 error.
Annoyingly and somewhat confusingly everything worked perfectly in development, does it always, and then you deploy and it all goes south very quickly.
I couldn’t even directly browse to the images, and having tried just about every variation of relative paths to the files, I knew that using images/filename.jpg, ./images/filename,jpg or even ../images/filename.jpg all worked just fine.
For a while I was hung up on file types and tried .png, .gif, .jpg, .jpeg and .webp and again unsurprisingly no problems here either.
My hosting company Everleap even took some time to see if was some weird configuration I had messed up, but besides noting that disabling the web.config file and finding that it was now possible to browse to the images, I was clueless as to what feat of stupidity I had pulled off.
Then believing that Blazing was somehow creating some kind of reference or mapping of the image assets I looked again at all the setup, config files and then I saw it in the program.cs file
app.MapStaticAssets();
As I had started the project with the sample files, this had automatically been included and I had simply been oblivious.
It didn’t take long to find out that MapStaticAssets is a new feature of .Net 9 that optimises the delivery of static assets, which I guess is great if your project is not going to be adding any files after deployment. Unfortunately not a particular common outcome for most of my clients, in which case you should be using app.UseStaticFiles(); instead.
And that was it everything now works just fine.
Anyway I bet I’m not the only one who will fall for this rather trivial mistake and I hope that I save someone from stressing and wasting a few hours trying to figure out what on earth they have done.