Search code examples
.net-corekestrel

How to run a .NET Core API app from a custom web application directory, not just root?


I have a .NET Core 2.0 MVC and API application. The application is accessible from the web root, e.g. localhost:51672/, localhost:51672/Home, localhost:51672/api/.... I would like to have an option to run from a different web application directory, e.g localhost:51672/custom, localhost:51672/custom/Home, localhost:51672/custom/api/...

I am assuming there is some option in Kestrel or when dotnet run is called, but unable to find it. Prefer not to have to modify several places in code for this to work, would prefer configurable or runtime option instead of having to hardwire a custom root path in code several places.

Below worked with the "custom" root except for swagger

app.UseSwaggerUI(c =>
{
  c.SwaggerEndpoint("/swagger/v1/swagger.json", "FusionVM V1");
});

app.UseMvc( routes =>
{
   routes.MapRoute(
            name: "default",
            template: "custom/{controller=Home}/{action=Index}/{id?}");
            }
    );

For web api, was able to get this to work using Route attribute on the Contoller, though really prefer not to have to specify a root path in all controllers. In dev, use "/" while on production available from custom web app directory.

[Route("custom/api/[controller]")]
public class MyController : Controller
    

Solution

  • Found something that works. In the Startup.cs added the following...

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

    This worked for MVC and Web Api. For Swagger, had to modify its json endpoint..

        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/custom/swagger/v1/swagger.json", "My API");
        });