httpcontext Class giving path as /:undefined in Asp.Net Core Web API Project

Ali basha Syed 20 Reputation points
2025-03-07T11:12:27.09+00:00

We have an Web API (.Net Core) application installed in Test and PROD server,

we are logging incoming request paths, using httpcontext Class.

But this class is giving path as /:undefined, sometimes as

/struts2-showcase/struts/inputtransfersselect.js,

/struts2-showcase/token/transfer4.action,

/index.action/struts/utils.js etc...

Where as in local, I am getting Path as /swagger/index.html, when I run API in Swagger, which is expected.

Why this is happening, how to avoid these urls hitting our API and resolve this problem. Thanks.

Below is the code of Program and Startup classes.

public static class Program
{
	public static void Main(string[] args)
	{		
		CreateHostBuilder(args).Build().Run();

	}

	public static IHostBuilder CreateHostBuilder(string[] args) =>
		Host.CreateDefaultBuilder(args)

			.ConfigureWebHostDefaults(webBuilder =>
			{

				webBuilder.UseIISIntegration();
				webBuilder.UseStartup<Startup>();

			});

}

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
        CreateMSSqlLogger(Configuration);
        AssignQueueDetails(Configuration);
    }
    public IConfiguration Configuration { get; }
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // for get appsettings from anywhere
        services.AddSingleton(Configuration);
        services.AddSingleton<IHostedService, SchedulerHelper>();
        services.AddSingleton<ISchedulerMasterDAL, SchedulerMasterDAL>();
        services.AddScoped<IAccountDAL, AccountDAL>();
        services.AddScoped<IMasterDAL, MasterDAL>();
        services.AddScoped<ISecurityDAL, SecurityDAL>();
        services.AddScoped<IOpportunityDAL, OpportunityDAL>();
        services.AddScoped<IOpportunityUserRoleDAL, OpportunityUserRoleDAL>();
        services.AddScoped<IQuotationDAL, QuotationDAL>();
        services.AddSingleton<ILoggerData, LoggerData>();
        services.AddControllers();
        // The following line enables Application Insights telemetry collection.
      //  services.AddApplicationInsightsTelemetry();
        //// Register the Swagger generator, defining 1 or more Swagger documents
        ///
        services.AddSwaggerGen(swagger =>
        {
            //This is to generate the Default UI of Swagger Documentation
            swagger.SwaggerDoc("v1.0", new OpenApiInfo
            {
                Version = "v1.0",
                Title = Configuration.GetValue<string>("Tittle"),
                Description = "ASP.NET Core 3.1 Web API"
            });
            // To Enable authorization using Swagger (JWT)
            swagger.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
            {
                Name = "Authorization",
                Type = SecuritySchemeType.ApiKey,
                Scheme = "Bearer",
                BearerFormat = "JWT",
                In = ParameterLocation.Header,
                Description = "JWT Authorization header using the Bearer scheme. \r\n\r\n Enter 'Bearer' [space] and then your token in the text input below.\r\n\r\nExample: \"Bearer 12345abcdef\"",
            });
            swagger.AddSecurityRequirement(new OpenApiSecurityRequirement
            {
                {
                      new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id = "Bearer"
                            }
                        },
                      #pragma warning disable CA1825
                        new string[] {}
                      #pragma warning restore CA1825
                }
			});
        });
      
        services.AddAuthentication(option =>
        {
            option.DefaultAuthenticateScheme = "bearer";
            option.DefaultChallengeScheme = "bearer";
        }).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                RequireExpirationTime=true,
                ValidIssuer = Configuration["Jwt:Issuer"],
                ValidAudience = Configuration["Jwt:Issuer"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) //Configuration["JwtToken:SecretKey"]
            };
            options.Events = new JwtBearerEvents
            {
                OnAuthenticationFailed = context =>
                {
                    if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                    {
                        context.Response.Headers.Append("Token-Expired", "true");
                    }
                    return Task.CompletedTask;
                }
            };
        });
        services.AddHealthChecks()
           	.AddCheck<CustomHealthCheck>("Service Status",
           	   failureStatus: HealthStatus.Unhealthy);
    }
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseMiddleware<LoggerHelper>();
        //app.UseHttpsRedirection();
        app.UseRouting();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
        app.UseAuthentication();
        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1.0/swagger.json", "My Demo API (V 1.0)");
        });
        app.UseHealthChecks("/health",
               new HealthCheckOptions
               {
                   Predicate = _ => true,
                   ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
               });
    }
    public static void CreateMSSqlLogger(IConfiguration configuration)
    {
        Common.Connectionstring = configuration.GetValue<string>(Common.SulpriceDBConnectionstring);
        Common.scheduletimimgs = configuration.GetValue<string>("ScheduleTimings");
        var connectionString = Common.Connectionstring; //  @"Server=sulpricelocal.database.windows.net;User Id=sulpriceuser;Password=test@123;Database=sulprice;";
        var tableName = "tbl_CRM_ErrorLogs";
        var columnOption = GetSqlColumnOptions();
        Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Error()
                         .MinimumLevel.Override("Sulzer.SulpriceAPI", LogEventLevel.Error)
                        .WriteTo.MSSqlServer(connectionString, tableName, columnOptions: columnOption, autoCreateSqlTable: true)
                        .CreateLogger();
    }
    public static ColumnOptions GetSqlColumnOptions()
    {
        var colOptions = new ColumnOptions();
        colOptions.Store.Remove(StandardColumn.Id);
        colOptions.Store.Remove(StandardColumn.Properties);
        colOptions.Store.Remove(StandardColumn.MessageTemplate);
        colOptions.Store.Remove(StandardColumn.Message);
        colOptions.Store.Remove(StandardColumn.Exception);
        colOptions.Store.Remove(StandardColumn.TimeStamp);
        colOptions.Store.Remove(StandardColumn.Level);
        colOptions.AdditionalDataColumns = new Collection<DataColumn>
            {
                //new DataColumn{DataType = typeof(Guid), ColumnName = "Id"},
                new DataColumn{DataType = typeof(Guid), ColumnName = "RequestId"},
                new DataColumn{DataType = typeof(string), ColumnName = "RequestObject"},
                new DataColumn{DataType = typeof(string), ColumnName = "ErrorMessage"},
                new DataColumn{DataType = typeof(string), ColumnName = "Stacktrace"},
                new DataColumn{DataType = typeof(DateTime), ColumnName = "ErrorOccuredDateTime"},
            };
        return colOptions;
    }
    public static void AssignQueueDetails(IConfiguration configuration)
    {
        QueueHelper.AssignQueueDetails(configuration);
    }
}

Developer technologies | ASP.NET | ASP.NET Core
{count} votes

2 answers

Sort by: Most helpful
  1. Danny Nguyen (WICLOUD CORPORATION) 6,045 Reputation points Microsoft External Staff Moderator
    2025-08-15T07:47:51.9866667+00:00

    Hello,

    I understand you’re seeing unexpected request paths in your ASP.NET Core Web API logs — sometimes showing as /:undefined or Struts-style URLs like /struts2-showcase/.... You also mentioned that locally you see only expected paths (e.g., /swagger/index.html), but in Test/Prod, the logs include these strange entries.

    I think here’s what’s going on:

    • These unusual paths are not generated by your application.
    • They come from external traffic — often automated bots, vulnerability scanners, or misconfigured clients probing your public endpoints.
    • Paths like /struts2-showcase/... are typically attempts to find and exploit known vulnerabilities in Apache Struts (which your app isn’t using).
    • /:undefined usually originates from malformed requests, where the client substituted an uninitialized value in the URL.
    • Locally you don’t see them because your development machine is not exposed to the public internet.

    Why HttpContext.Request.Path shows them

    HttpContext simply reports the exact path that the client requested — even if it’s invalid or meaningless. In other words, your logging middleware is doing its job correctly.


    Recommended Actions

    1. Fix middleware ordering

    Correct ordering ensures HttpContext is populated consistently before logging. For example:

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
     
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1.0/swagger.json", "My Demo API (V 1.0)");
    });
     
    // Redirect root to Swagger
    app.Use(async (context, next) =>
    {
        if (context.Request.Path == "/")
        {
            context.Response.Redirect("/swagger/index.html");
            return;
        }
        await next();
    });
     
    // Early filter for unwanted paths
    app.Use(async (context, next) =>
    {
        var path = context.Request.Path.Value?.ToLowerInvariant() ?? "";
        if (path == "/:undefined" || path.Contains("struts2") || path.EndsWith(".action"))
        {
            context.Response.StatusCode = StatusCodes.Status404NotFound;
            await context.Response.WriteAsync("Not Found");
            return;
        }
        await next();
    });
     
    // Logging middleware
    app.UseMiddleware<LoggerHelper>();
     
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
     
    app.UseHealthChecks("/health", new HealthCheckOptions
    {
        Predicate = _ => true,
        ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
    });
     
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
    

    This:

    • Serves Swagger by default
    • Filters bot/malformed requests early
    • Runs logging after routing/auth context is established

    1. Filter logs

    If you want to keep logging everything but avoid polluting logs, add logic in LoggerHelper to mark or skip suspicious paths.


    1. Block at the edge

    For best performance, configure URL filtering at:

    • IIS: URL Rewrite rules
    • Nginx/Apache: location blocks or rewrite rules
    • Azure App Gateway / WAF: custom rules matching suspicious patterns

    This prevents bad requests from ever reaching your app.


    Conclusion

    The / : undefined paths are caused by external, malformed requests and are expected on internet-facing APIs. Your application is not generating them. The resolution is to:

    1. Ensure middleware order is correct for consistent logging.
    2. Filter or tag suspicious requests in middleware.
    3. Optionally block these requests at the network/proxy layer.

    Hope this helps.

    1 person found this answer helpful.

  2. Bruce (SqlWork.com) 82,321 Reputation points Volunteer Moderator
    2025-03-07T16:48:28.61+00:00

    If you also logged the referer header you might get the source. It likely some webpage. with the undefined, I'd guess the url was created with javascript.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.