Home > Enterprise >  Run multiple AspNetCore WebApi on same port (not in IIS)
Run multiple AspNetCore WebApi on same port (not in IIS)

Time:10-29

We have a pool of .Net 4.7.2 WebApis which we host with nuget Microsoft.Owin.Hosting (not in IIS). All these programs and their web controllers listen on the same port but different virtual paths, e.g. http://ourserver:4711/ServiceA/ and http://ourserver:4711/ServiceB/ The Owin nuget for 4.7.2 seems to create a host in memory when the first service starts and all others just register their virtual paths and everything gets routed just fine.

Reason for using a single port are firewall rules and load balancing etc.

Now we try to migrate to .Net6 and while there is a nuget Microsoft.AspNetCore.Owin we can't get it to work. For testing we're using the sample WheatherForecastController

Goal 1) We want it to listen on the virtual path http://localhost:4711/ServiceA/ but not on the root path http://localhost:4711 at which we fail already.

Goal 2) Start a second, independent exe which then listens on http://localhost:4711/ServiceB/

Here's the basic setup for the Owin package that we have so far and we've played with all kinds of settings which don't seem to have any effect for our purposes.

public static void Main()
{
    var host = new WebHostBuilder()
        .UseUrls("http://localhost:4711/")        
        .UseKestrel()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}

public sealed class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddMvc(sa =>
        {
            sa.EnableEndpointRouting = false;
        });
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UsePathBase("/ServiceA")
           .Use((context, next) =>
           {
               context.Request.PathBase = "/ServiceA";
               return next();
           })
           .UseRouting()
           .UseMvc()
           .UseOwin();
    }
}

CodePudding user response:

Yay, we figured it out, with the help of this answer

We can't use Kestrel but since we live in a Windows-only environment, we don't need to. We can revert to the old HttpSys for this and then it works. Basic setup:

var builder = WebApplication.CreateBuilder();

#pragma warning disable CA1416 // Validate platform compatibility
builder.WebHost.UseHttpSys(o => // Windows only
{
    o.UrlPrefixes.Add("http://localhost:4711/ServiceA"); //unique virtual path
});
#pragma warning restore CA1416
  • Related