Search code examples
asp.net-corepostmanx509certificate.net-8.0

Calling controller results in http 404 error: unable to verify the first certificate


I'm new to .NET standard & .NET Core platforms. I'm trying to create and test a Web API project using VS Code. I created the application using the following command

dotnet new webapi -o dontNetKarImpl -f net8.0

Initially, there was a minimal API present by default.

During debugging, I found a peculiar warning. The Minimal API using app.MapGet was working fine

mapget working fine

But for the controller, I added Postman gave me unable to verify certificate warning.

Unable to verify first certificate!

On executing dotnet run, I was able to get the following result:

weatherforecast response

Then I proceeded to add a controller of my own. Here are the controller, models & DbContext:

Controller code with Controller name highlighted to show there is no typo

Model

DBContext

I proceeded to build and run the new controller on Postman, I get a http 404 error:

new controller 404

I searched online for solution where people told it could be a controller typo or a DB initialization problem.

If it is a typo, then Swagger would not show it right? But Swagger picks up the controller

Swagger picks up the controller, but it also gives 404

I added some code to check if there is any problem with init. The connection URL, but I don't think so. According to this code, it can communicate with the database:

DB connection established

For the certificate issue, I did the following: using the following code I tried to create the .pem certificate:

# Find the certificate's thumbprint (in certmgr.msc or similar)
$thumbprint = "YOUR_CERT_THUMBPRINT"  

# Export from the store
Export-Certificate -Cert Cert:\LocalMachine\My\$thumbprint -FilePath localhost.crt 

# Convert CRT to PEM (may need OpenSSL installed)
openssl x509 -inform der -in localhost.crt -out localhost.pem

which the VS Code auto prompted to generate a certificate when I tried to run the project first time.

dotnet dev-certs https --trust

pem vretificate

Even after placing the certificate, Postman still shows the same issue.

If the problem is the certificate, shouldn't that apply to the inbuilt API too? If it's a certificate issue why does Default API work and mine doesn't?

Any help will be greatly appreciated.

I don't know if this is on any help here is the program.cs, I don't know if I had made any mistakes here:

using System.Security.Authentication;
using KaromiTest.Data;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddControllers();
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddDebug();

// builder.WebHost.ConfigureKestrel(options =>
// {
//     options.ListenAnyIP(5001, listenOptions =>
//     {
//         listenOptions.Protocols = HttpProtocols.Http1AndHttp2AndHttp3;
//         listenOptions.UseHttps(adapterOptions =>
//         {
//             adapterOptions.SslProtocols = SslProtocols.Tls12; // Explicitly set TLS 1.2
//         });
//     });
// });
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthentication();
app.UseAuthorization();
app.UseHttpsRedirection();

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    //string connectionString = "YourConnectionString"; // Replace with your actual string

    try
    {
        using (var dbContext = new AppDbContext(new DbContextOptionsBuilder<AppDbContext>()
        .UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")).Options))
        {
            // A simple way to test if we can access the database
            var canConnect = dbContext.Database.CanConnect();
            Console.WriteLine(canConnect ? "Connection successful!" : "Connection failed!");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Connection failed: " + ex.Message);
    }
    var forecast = Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();

app.Run();

record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

Solution

  • In your Program.cs you are missing this line of code :

    app.MapControllers();
    

    As from right now your app is only configured to use minimal api's.

    You can always manipulate your route with RouteAttribute so your base route for your controller is [Route("api/[controller]")](This can be only [Route("api")] if you wish) which is a base route for all of your endpoint in that controller. You can add additional route above your action method something like [Route("/getcopysheets")] then your route will be http://localhost:5050/api/copysheets/getcopysheets.

    If you are new to this I would advise to look deeper into documentation.