
<h3>Question</h3>
The default Blazor approach to 404 is to create a soft 404 in App.razor, but I would like to adhere to search engine best practices to actually return the 404 status code while displaying a 404 page on Azure.
I tried to remove the element in App.razor to see if I could force a 404, however, that did not compile.
Any suggestions?
<h3>Answer1:</h3>
I was able to return 404 http status codes when using server side prerendering in the Blazor WebAssembly App (ASP.Net Core Hosted) Template
When I pointed the browser to http://localhost/fetchdata it returned a page. I wanted this to return a 404 status code as an example. This was possible using dependency injection and a stub class.
In BlazorApp1.Client I added a IResponse.cs file:
namespace BlazorApp1.Client {
public interface IResponse {
void SetNotFound();
}
}
In BlazorApp1.Client I added a ResponseStub.cs file:
namespace BlazorApp1.Client {
public class ResponseStub : IResponse {
public void SetNotFound() {
// Do nothing if we are browser side
}
}
}
In FetchData.razor in BlazorApp1.Client I added:
@inject BlazorApp1.Client.IResponse Response
and in the code section:
protected override void OnInitialized() {
Response.SetNotFound();
}
In Program.cs in BlazorApp1.Client I added:
builder.Services.AddScoped<IResponse, ResponseStub>();
Then in BlazorApp1.Server, in Startup.cs I added under ConfigureServices:
services.AddHttpContextAccessor();
services.AddScoped<IResponse, Response>();
and under Configure I replaced:
endpoints.MapFallbackToFile("index.html");
with:
endpoints.MapFallbackToPage("/_Host");
Then create the Server implementation of IResponse in Response.cs:
using BlazorApp1.Client;
using Microsoft.AspNetCore.Http;
using System.Net;
namespace BlazorApp1.Server {
public class Response : IResponse {
private readonly IHttpContextAccessor _httpContextAccessor;
public Response(IHttpContextAccessor accessor) {
_httpContextAccessor = accessor;
}
public void SetNotFound() {
_httpContextAccessor.HttpContext.Response.StatusCode = (int)HttpStatusCode.NotFound;
}
}
}
And finally I create a _Host.cshtml file in BlazorApp1.Server/Pages:
@page "/fallback"
@namespace BlazorPrerendering.Server.Pages
@using BlazorApp1.Client
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = "_Layout";
}
<app>
<component type="typeof(App)" render-mode="ServerPrerendered" />
</app>
<div id="blazor-error-ui">
An unhandled error has occurred.
<a href="" class="reload">Reload</a>
<a class="dismiss">