Configure SPA Routing in .NET Core Application
September 26, 2019•90 words
When serving a Single Page Application (SPA) from a .NET Core service which also contains an API some configuration is required to return the SPA for relevant requests.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Use(async (context, next) =>
{
string path = context.Request.Path.Value;
if (!path.StartsWith("/api") && !Path.HasExtension(path))
{
/*
If this is not an API request or a request for static content (e.g. css/javascript)
then return the index.html of the SPA
*/
context.Response.ContentType = "text/html";
await context.Response.SendFileAsync("path/to/index.html");
}
else
{
await next.Invoke();
}
});
// ...
}