I am new to .NET Core web API development and have recently started working on a project at my company. I cloned a .NET Core 6.0 web API project from GitHub and I am trying to run it locally. However, when I test it using Postman, the breakpoints in my code are not being hit. I am currently working behind my company's proxy, but I have disabled all proxies and SSL settings in Postman. Despite my efforts, I have been unable to make the API hit my code when sending a request from Postman.
I have been attempting to troubleshoot this issue for several days, but have not been able to find a solution. I am unsure why the code is not being hit when I send a request from Postman, and I am unsure what might be causing this blockage.
Additionally, I receive a "Notification: Gateway Timeout" error when trying to test the API in Postman. Since this is a development environment, I believe I do not need to pass a bearer token. I have tried sending requests both with and without a token, but nothing seems to change.
It's worth mentioning that I have bypassed the default port (8080) and added a custom logger, which seems to prevent Swagger from opening in the development environment. However, when I test the API using Postman, this issue arises.
I would greatly appreciate any help or guidance in resolving this problem. Thank you in advance for your assistance.
What I have tried:
am running in post man- http://localhost:8080/saveRoom
passing header as Entitlement and
body like
{ "Id": "example_id", "Entitlement": "example_entitlement", "Filename": "example_filename", "Timestamp": "2023-06-27T12:00:00" }
my program.cs class
public class Program
{
static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
.ReadFrom.Configuration(hostingContext.Configuration)
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.Fluentd("fluentd.rx-system.svc.cluster.local", 24284, "myappAppService"))
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseStartup<Startup>()
.UseUrls("http://*:8080")
.ConfigureKestrel(serverOptions =>
serverOptions.ConfigureHttpsDefaults(options =>
options.OnAuthenticate = (_, authenticationOptions) =>
authenticationOptions.CipherSuitesPolicy = new CipherSuitesPolicy(
new[]
{
TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
TlsCipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
TlsCipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
})));
});
}
my launch setting.json
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:36959",
"sslPort": 44392
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"WebApp": {
"commandName": "Project",
"dotnetRunMessages": "true",
"launchBrowser": true,
"launc
hUrl": "swagger",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
my startup class
using System;
using System.Threading.Tasks;
using AspNetCoreRateLimit;
using IdentityModel.AspNetCore.OAuth2Introspection;
using webapp.Controllers;
using webapp.DataModel;
using webapp.Repository;
using webapp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace webapp
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
private IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
var openIdConfiguration = Configuration.GetSection("OpenID");
var baseUrl = openIdConfiguration.GetSection("BaseURL").Value;
var clientId = openIdConfiguration.GetSection("ClientID").Value;
var clientSecret = openIdConfiguration.GetSection("ClientSecret").Value;
var serviceProvider = services.BuildServiceProvider();
var logger = serviceProvider.GetService<ILogger<Startup>>();
services.AddDistributedMemoryCache();
services.AddAuthentication(OAuth2IntrospectionDefaults.AuthenticationScheme)
.AddOAuth2Introspection(options =>
{
options.EnableCaching = true;
options.CacheDuration = new TimeSpan(0, 1, 0, 0);
options.Authority = baseUrl;
options.ClientId = clientId;
options.ClientSecret = clientSecret;
options.Events.OnAuthenticationFailed = ctxt =>
{
logger.LogInformation($"Authentication failure for {ctxt?.Principal?.Identity?.Name}");
return Task.CompletedTask;
};
});
services.AddOptions();
services.Configure<IpRateLimitOptions>(Configuration.GetSection("IpRateLimiting"));
services.AddSingleton<IIpPolicyStore, DistributedCacheIpPolicyStore>();
services.AddSingleton<IRateLimitCounterStore, DistributedCacheRateLimitCounterStore>();
services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
services.AddDistributedRateLimiting<AsyncKeyLockProcessingStrategy>();
services.AddControllers();
services.AddSingleton(Configuration);
services.AddDbContext<RoomDbContext>(optionsBuilder =>
optionsBuilder.UseNpgsql(Configuration.GetConnectionString("RoomDb"),
options => options.EnableRetryOnFailure()));
services.AddSingleton<IAuthenticationService>(provider =>
new AuthenticationService(baseUrl, provider.GetRequiredService<ILogger<AuthenticationService>>()));
services.AddScoped<IS3Repository, S3Repository>(provider =>
new S3Repository(
provider.GetRequiredService<ILogger<S3Repository>>(),
Configuration));
services.AddScoped<IRoomDataService, RoomDataService>(provider =>
new RoomDataService(
provider.GetRequiredService<ILogger<RoomDataService>>(),
provider.GetRequiredService<RoomDbContext>(),
provider.GetRequiredService<IS3Repository>()));
services.AddScoped<ApiExceptionFilter>();
services.AddMvc(options =>
{
options.InputFormatters.Insert(0, new RawJsonBodyInputFormatter());
});
services.AddSwaggerGen();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
using var scope = app.ApplicationServices.CreateScope();
var services = scope.ServiceProvider;
var dbContext = services.GetRequiredService<RoomDbContext>();
dbContext.Database.EnsureCreated();
try
{
var databaseCreator = dbContext.Database.GetService<IDatabaseCreator>() as RelationalDatabaseCreator;
databaseCreator.CreateTables();
}
catch (Exception ex)
{
Console.WriteLine("Error while creation database tables (maybe they exist already?)");
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseIpRateLimiting();
app.Use(async (context, next) =>
{
context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
context.Response.Headers.Add("Strict-Transport-Security", "max-age=31536000; includeSubdomains");
await next();
});
if (env.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseEndpoints(endpoints =>
{
if (env.IsDevelopment())
{
}
else
{
endpoints.MapControllers();
}
});
}
}
}
controller method
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web;
using webapp.DataModel;
using webapp.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
namespace webapp.Controllers
{
[Authorize]
[ApiController]
[Route("/")]
[ServiceFilter(typeof(ApiExceptionFilter))]
public class RoomDataController : ControllerBase
{
private const string ROOM_SCHEMA_LOCATION = "Schemas/room.schema.json";
private readonly ILogger<RoomDataController> _log;
private readonly IRoomDataService _roomDataService;
private readonly JSchema _roomSchema;
public RoomDataController(ILogger<RoomDataController> log, IRoomDataService roomDataService)
{
_log = log;
_roomDataService = roomDataService;
_roomSchema = JSchema.Parse(System.IO.File.ReadAllText(ROOM_SCHEMA_LOCATION));
}
[HttpPost("saveRoom")]
public async Task<ActionResult<RoomMetadata>> SaveRoom([FromBody] string roomData)
{
Request.Headers.TryGetValue("Entitlement", out var entitlement);
roomData = HttpUtility.UrlDecode(roomData);
if (string.IsNullOrWhiteSpace(entitlement) || string.IsNullOrWhiteSpace(roomData))
{
_log.LogWarning($"POST /saveRoom without entitlement");
return BadRequest();
}
_log.LogInformation($"POST /saveRoom entitlement={entitlement}");
var roomObject = JObject.Parse(roomData);
if (!roomObject.IsValid(_roomSchema))
{
return BadRequest();
}
return await _roomDataService.SaveRoom(entitlement, roomData);
}
}
}
i am running in post man- http:
passing header as Entitlement and
body like
{
"Id": "example_id",
"Entitlement": "example_entitlement",
"Filename": "example_filename",
"Timestamp": "2023-06-27T12:00:00"
}