.Net Core WebAPI redirection to Angular

  Kiến thức lập trình

It Seems the Angular redirection from with-in .Net Core web API is not working in a shared deployment. I am using .Net Core 7 for the web api. The current setup works perfectly with .Net Core 6.
Below image shows my build files structure (Image 1).
Build Files Structure

.Net Core Web API build files are shown in above image
wwwroot folder from above image contains the angular build files.

enter image description here
Above image shows angular build files.
Below shows the webapi program.cs code

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.Use(async (context, next) =>
{
    await next();
    if (context.Response.StatusCode == 404 &&     !System.IO.Path.HasExtension(context.Request.Path.Value))
    {
        context.Request.Path = "/index.html";
        await next();
    }
});
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();

I am aware below lines of code from program.cs is responsible to redirect the request to angular application when the requested URL doesn’t match with any of the end points.

app.Use(async (context, next) =>
{
    await next();
    if (context.Response.StatusCode == 404 && !System.IO.Path.HasExtension(context.Request.Path.Value))
    {
        context.Request.Path = "/index.html";
        await next();
    }
});

I have deployed the above folder structure (Image 1) to an Azure App Service.
When I hit https://sitename.azurewebsites.net/weatherforecast I get the API response.
However when I hit https://sitename.azurewebsites.net, Since not such endpoint exists in the webapi, I expect the request to be redirected to index.html inside the wwwroot folder so that the Angular page is rendered. But I get 404 Not Found error.

When I host webapi (https://sitenameapi.azurewebsites.net) and angular app (https://sitenameangularapp.azurewebsites.net) as 2 separate Azure App Service (Of course I handled the CORS part), the application works. I suspect the redirection from API to APP is the rootcause, however I am not able to resolve it. Any help would be greatly appreciated.

LEAVE A COMMENT