1

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

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

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它运行项目时,它成功启动,但每当我尝试在 route 上发出 POST 请求时/register,我都会收到如下所示的错误...

在此处输入图像描述

4

2 回答 2

1

问题出在连接字符串中。要指定用户,您需要使用“用户 ID”而不是“用户”。在您的 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"
于 2022-02-21T12:45:02.687 回答
0

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

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

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

于 2022-02-23T16:32:50.537 回答