Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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

C#
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

C#
{
  "$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

C#
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())
                {
                    // endpoints.MapControllers().WithMetadata(new AllowAnonymousAttribute());
                }
                else
                {
                    endpoints.MapControllers();
                }
            });
        }
    }
}


controller method

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



C#
i 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"
}
Posted
Updated 28-Jun-23 3:05am
Comments
Graeme_Grant 28-Jun-23 1:14am    
Breakpoints are hit if the endpoint is reached and the routing points to the correct method. It is suggesting that you have an issue at one of these points in your code.

Fire up a new default test app and set a breakpoint in that to see if that works.

This is a company app? Then you need to get company help. You are being paid to work on the app, not us.
Jithu_007 28-Jun-23 1:50am    
sorry for the confusion.this is not company app.i am using company laptop to learn the api which is under proxy.I have created a new boiler plate code when we creating a new web api solun.that is hitting when i use swagger but not hitting when i test with postman getting 504 gateway error
Graeme_Grant 28-Jun-23 2:01am    
Why state this then? To quote you: "I am new to .NET Core web API development and have recently started working on a project at my company."

The out of the box samples work. You need to get those to work first before progressing onto what you have posted in your question. Lean to walk first before you run.

1 solution

with postman getting 504 gateway error
Your breakpoints are never getting hit because the request is never getting to the controller. You have to solve the 504 error first before you can start debugging the code in the controller.

This can come down to policy in your company environment, mandating proxy configuration, firewall configuration blocking the request, or a configuration problem in your service startup code, or a combination of those problems.

The 504 Gateway Timeout means there is not one character of a response coming back for the request and Postman gets tired of waiting.
 
Share this answer
 
Comments
Jithu_007 28-Jun-23 15:45pm    
When i am using swagger break point is hitting. But when i use postman nothing happens bit 504 coming. I have severel headers that easy to pass from postman.
Dave Kreskowiak 28-Jun-23 17:03pm    
There's probably a header that is not being passed by Postman but is in the request sent by the browser when using Swagger.
Jithu_007 29-Jun-23 12:36pm    
i am passing everything in postman .same i have passed in thunderclient tool,it got worked.but y not in postman
Dave Kreskowiak 29-Jun-23 12:59pm    
Because there's a header missing or the session isn't configured to use whatever authentication method your API is expecting.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900