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);
    }
}

ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
396 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 72,276 Reputation points
    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 Answers by the question author, which helps users to know the answer solved the author's problem.