我正在尝试使用 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
,我都会收到如下所示的错误...