How to host a asp .net core application under a sub folder

Viewed 11291

I have a asp .net core app running on Linux using Kestrel.

It binds to the ip ok on port 80.

But the nginx reverse proxy site needs to host the app under a non-root path e.g.

http://somesite.com/myapp

So this is ok, the app loads, but the app does not know about the myapp path - so tries to load content path resources from root. Therefore css resources etc don't load.

How do I configure the app ideally at runtime to know about the url path.

Update:

I have found that in Startup.configure using app.UsePathBase("/myapp"); helps as the app will handle the request on this path OK - but the static file requests are then /myapp/images/example.jpg which return a 404.

The images folder is in wwwroot - the default as I understand it for UseStaticFiles.

I would have expected the request to understand that /myapp was in effect virtual.

4 Answers

OK - so 2 things had to be done to get the app running under a "virtual directory":

Inside the startup configure method I had to set the basepath for the app AND specify a path for the static files.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
 ...
 app.UseStaticFiles("/myapp");
 app.UsePathBase("/myapp");
 ...
}

The app also runs from / as well - not sure if this is desirable but its not a big issue for me right now.

For me (using .NET Core 3.1) it was a bit different, using ScottC's answer it failed to find the static files as it was looking in the root of the my-app directory, not in my-app/wwwroot

This config worked for me in Startup.cs:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...
    if (env.IsDevelopment())
    {
        ...
    }
    else
    {
        ...
        app.UsePathBase("/my-app");
    }

    app.UseStaticFiles();
    ...

}

ScottC,

Once your web content is under wwwroot you have to add app.UseStaticFiles() on the configure section on Startup class.

See the example below:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseStaticFiles();
}

Hope to have helped you.

Besides setting the app.UsePathBase("/my-app"); what i had to do is to add a line to Program:

     public static void Main(string[] args)
        {
            CreateHostBuilder(args)
#if !DEBUG
                .UseContentRoot(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location))
#endif
                .Build().Run();
        }
Related