Skip to content

Setting up HttpSys with Base Path #13028

@dannyfhalpotia

Description

@dannyfhalpotia

I've tried out many different ways of setting the base path when using HttpSys but none seems to work once it gets deployed to a windows server. The funny thing is that my app is getting hit because the middleware is getting triggered. So https://localhost:30310/SomeBasePath (localhost on the server) will give a API IS RUNNING response and the same with app.Run for 404s.

The issue seems to be that ALL paths to my controllers resolve to a 404 and in the logs I get:

Microsoft.AspNetCore.Builder.RouterMiddleware|Request did not match any routes

However, on my local machine it works fine and the route is matched. I also have the base path set up locally but one main difference is that I'm just using HTTP locally. I don't think the scheme is the problem as otherwise I wouldn't get to my application at all.
Some of my code:

Program.cs CreateWebHostBuilder()

public static IWebHost CreateWebHostBuilder(string[] args)
{
    IHostingEnvironment env = null;

    var builder =
        WebHost.CreateDefaultBuilder(args)
         .UseStartup<Startup>()
         .ConfigureAppConfiguration((hostingContext, config) =>
         {
             env = hostingContext.HostingEnvironment;
         })
         .UseHttpSys(options =>
         {
              options.Authentication.AllowAnonymous = true;
              if (!env.IsDevelopment())
              {
                  //options.UrlPrefixes.Add("https://*:30310/SomeBasePath/");
                  options.UrlPrefixes.Add("https://*:30310/");
              }
              else
              {
                  options.UrlPrefixes.Add("http://localhost:5000/SomeBasePath/"); //works fine
              }
         })
         .ConfigureLogging(b =>
         {
             //ommitted
         })
         .UseNLog()
         .Build();
    
    return builder;
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    //IoC and DB context init ommitted
    
    services.AddCors(c => 
    {
        c.AddPolicy("AllowOrigin", options => 
               options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
    });

    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UsePathBase(new PathString("/SomeBasePath"));
    app.UseCors("AllowOrigin");

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

   app.UseMvc();

    app.Use((context, next) =>
    {
        if (context.Request.Path.Value == "" || context.Request.Path.Value == "/")
        {
            context.Response.ContentType = "text/plain";
            return context.Response.WriteAsync("API IS RUNNING");
        }
        return next.Invoke();
    });

    app.Run(context =>
    {
        context.Response.StatusCode = 404;
        context.Response.ContentType = "application/json";

        _logger.Debug("Request Method: {METHOD}", context.Request.Method);
        _logger.Debug("Request Scheme: {SCHEME}", context.Request.Scheme);
        _logger.Debug("Request Path: {PATH}", context.Request.Path);
        _logger.Debug("Request Path Base: {PATH BASE}", context.Request.PathBase);

        // Headers
        foreach (var header in context.Request.Headers)
        {
             _logger.Debug("Header: {KEY}: {VALUE}", header.Key, header.Value);
        }
        // Connection: RemoteIp
        _logger.Debug("Request RemoteIp: {REMOTE_IP_ADDRESS}",
        context.Connection.RemoteIpAddress);
       
        return context.Response.WriteAsync("{ \"message\": \"Not found!!! \" }");
    });

Simple controller:

    [Route("api/system")]
    [ApiController]
    public class SystemController : ControllerBase
    {
        
        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public IActionResult Get()
        {
            return Ok("Hello World");
        }
    }

So, a path to the above through GET https://localhost:30310/SomeBasePath/api/system on the server gives a 404 and logs that no routes were matched. In addition the logs produced in my 404 middleware tells me that request path is "api/system" and that the path base is "SomeBasePath", so it seems that it's doing the right splitting into path and path base but still not able to match the path against any controller which is super weird.

I've tried to add the base path to the UrlPrefix in Program.cs and leave out the app.UsePathBase but with no luck. Any idea where I'm going wrong?

I should also add that I'm using a gateway normally to call my API through that publicly, and I'm getting the exact same issue when going through the gateway, so I've just resorted to testing locally on the server to rule out any potential gateway issues.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-networkingIncludes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions