Home > Back-end >  Static files not served in Azure WebApp with .NET Core WebAPI
Static files not served in Azure WebApp with .NET Core WebAPI

Time:09-16

I deploy a .NET Core WebAPI application to an Azure WebApp. Also, into the same root folder I deploy a statically served React application with an accompanying index.html file:

Files and Folders

When trying to access this I get 404 errors on the root, as well as when I explicitly call /index.html

I already added the static file serve middleware:

var app = builder.Build();
app.UseCors();
app.UseHttpsRedirection();
app.UseFileServer();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

Interesting: When I edit the web.config file

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\MyAppWebService.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>

so that the <handlers><add path= uses an api prefix (like path="api"), the static files do get served (presumably because those requests then are not hitting the actual .NET Core WebAPI application.

I also added an "info"-endpoint to check the ContentRoot but everything seems fine there:

[ApiController]
public class InfoController : ControllerBase
{
    private readonly IConfiguration config;

    public InfoController(IConfiguration config)
    {
        this.config = config;
    }

    [Route("api/info")]
    [HttpGet]
    public IActionResult Info()
    {
        try
        {
            return Ok(new
            {
                ContentRoot = config.GetValue<string>(WebHostDefaults.ContentRootKey)
            });
        }
        catch (Exception exc)
        {
            return McClientUtils.CreateErrorResponse(exc);
        }
    }
}

Which yields as expected: {"contentRoot":"C:\\home\\site\\wwwroot\\"}

What do I need to do so the static files are served alongside the /api calls?

CodePudding user response:

You have to add few lines of code in middleware configuration.

For example, for static content placed in root (your case), simply use this code:

 app.UseFileServer(new FileServerOptions
{
    FileProvider = new PhysicalFileProvider(Directory.GetCurrentDirectory()),
    RequestPath = "",
    EnableDefaultFiles = true
});

Otherwise, if static contents are in a sub-dir (for example StaticFiles) just use this version:

app.UseFileServer(new FileServerOptions
{
    FileProvider = new PhysicalFileProvider(
               Path.Combine(Directory.GetCurrentDirectory(), "StaticFiles")),
    RequestPath = "/StaticFiles",
    EnableDefaultFiles = true
});
  • Related