I have a Blazor WASM app set up using the Visual Studio Template. My routing in the Startup.cs file for the Server project looks like this:
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html",);
});
This has been working great and serving the wwwroot/index.html file from my Client project any time I make a GET request a routes that I don't have a controller for. The Blazor framework in the Client project takes it for there. However, I now need to support returning the index.html file from both a GET or a POST request to endpoints in my app that I don't have a controller for. I'm having a really hard time figuring out how to set this up. I have tried the EndpointRouteBuilderExtensions.MapPost method and am able to return strings but don't see any good examples of using it to return files. This does not work:
endpoints.MapPost("*", (HttpContext context) => {
context.Request.Path = "/index.html";
context.SetEndpoint(null);
});
Although it's similar to what the framework method StaticFilesEndpointRouteBuilderExtensions.MapFallbackToFile does: https://github.com/dotnet/aspnetcore/blob/fc4e391aa58a9fa67fdc3a96da6cfcadd0648b17/src/Middleware/StaticFiles/src/StaticFilesEndpointRouteBuilderExtensions.cs#L194
My problem is similar to this one: How do I map an endpoint to a static file in ASP. NET Core? but answers there don't work for my situation.
CodePudding user response:
I have one way that could help you. You can tell the webserver to route any route it doesn't find to you index.html. The syntax in Nginx is
try_files $uri $uri/ /index.html =404;
Not sure if this will fix your issue, as I haven't tested this with Api controllers in Wasm.
CodePudding user response:
After more reading of the aspnetcore source and MapFallbackToFile I came up with this solution that works for me. My Server solution's Startup.Configure method has this:
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapPost("{*path:nonfile}", CreatePostIndexRequestDelegate(endpoints));
endpoints.MapFallbackToFile("index.html");
});
And I added this new method to that Startup class:
//This method allows Post requests to non-file, non-api endpoints to return the index.html file
private static RequestDelegate CreatePostIndexRequestDelegate(IEndpointRouteBuilder endpoints)
{
var app = endpoints.CreateApplicationBuilder();
app.Use(next => context =>
{
context.Request.Path = "/index.html";
context.Request.Method = "GET";
// Set endpoint to null so the static files middleware will handle the request.
context.SetEndpoint(null);
return next(context);
});
app.UseStaticFiles();
return app.Build();
}