如何在 .NET Minimal API 与 PostgreSQL 集成中解决此错误?

How do I resolve this error in .NET Minimal API integration with PostgreSQL?

我正在尝试使用 ASP.Net Minimal API 东西制作 APIs 并且我正在尝试使用 PostgreSQL 作为数据库,因此我正在关注 Article到目前为止,我一直在关注它,但我无法获得所需的输出。

我已经从我的项目中提供了以下所有文件...

Program.cs

using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");

builder.Services.AddDbContext<BookStoreDB>(options => options.UseNpgsql(connectionString));

builder.Services.AddDatabaseDeveloperPageExceptionFilter();

var app = builder.Build();

app.MapGet("/", () =>
{
    return "Hello World";
});

app.MapPost("/register", (BookStoreDB database, RegisterRequest body, HttpResponse response) =>
{
    User user = new User(1);
    user.FirstName = body.firstName;
    user.LastName = body.lastName;
    user.Email = body.email;
    user.Password = body.password;
    database.Users.Add(user);
    database.SaveChanges();
    response.StatusCode = 201;
    return new { requestBody = body };
});

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Port=5432;Database=BookStore;User=postgres;Password=somepass"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

BookStoreDB.cs

using Microsoft.EntityFrameworkCore;

public class BookStoreDB : DbContext
{
    public BookStoreDB(DbContextOptions<BookStoreDB> options) : base(options)
    {

    }

    public DbSet<User> Users => Set<User>();
}

RequestObjects.cs

public class LoginRequest
{
    public string email { get; set; } = default!;
    public string password { get; set; } = default!;
}

public class RegisterRequest
{
    public string firstName { get; set; } = default!;
    public string lastName { get; set; } = default!;
    public string email { get; set; } = default!;
    public string password { get; set; } = default!;
}

User.cs

public record User(int id)
{
    public string FirstName { get; set; } = default!;
    public string LastName { get; set; } = default!;
    public string Email { get; set; } = default!;
    public string Password { get; set; } = default!;
}

我不知道这些文件的用途以及它们的约定。但是当我 运行 使用 dotnet watch run 的项目成功启动时,但每当我尝试在 /register 路线上发出 POST 请求时,我会收到如下所示的错误...

问题出在连接字符串中。要指定用户,您需要使用“User Id”而不是“User”。在您的 appsettings.json 文件中尝试更改

"DefaultConnection": "Server=localhost;Port=5432;Database=BookStore;User=postgres;Password=somepass"

这个到

"DefaultConnection": "Server=localhost;Port=5432;Database=BookStore;User Id=postgres;Password=somepass"

由于提供的连接字符串错误,无法设置“用户”参数。在 appsettings.json 文件中按如下方式更新连接字符串:

 "ConnectionStrings": { 
"DefaultConnection":"User ID=postgres;Password=somepass;Host=localhost;Port=5432;Database=BookStore;CommandTimeout=100"
}

如果不需要,您可以忽略 CommandTimeout。