我是 .NET 标准和 .NET Core 平台的新手。我正在尝试使用 VS Code 创建和测试 Web API 项目。我使用以下命令创建了应用程序
dotnet new webapi -o dontNetKarImpl -f net8.0
最初,默认情况下存在一个最小的 API。
在调试过程中,我发现了一个奇怪的警告。使用
app.MapGet
的最小 API 工作正常
但是对于控制器,我添加了 Postman 给了我无法验证证书的警告。
执行
dotnet run
时,我得到以下结果:
然后我开始添加自己的控制器。这是控制器、型号和
DbContext
:
我继续在 Postman 上构建并运行新控制器,我收到 http 404 错误:
我在网上搜索解决方案,人们告诉我这可能是控制器拼写错误或数据库初始化问题。
如果是拼写错误,那么Swagger就不会显示对吧?但 Swagger 拿起了控制器
我添加了一些代码来检查init是否有问题。连接 URL,但我不这么认为。根据这段代码,就可以与数据库进行通信了:
对于证书问题,我执行了以下操作:使用以下代码我尝试创建
.pem
证书:
# 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
当我第一次尝试运行该项目时,VS Code 自动提示生成证书。
dotnet dev-certs https --trust
即使放置证书后,Postman仍然显示相同的问题。
如果问题出在证书上,那么这不也应该适用于内置 API 吗?如果是证书问题,为什么默认 API 可以工作而我的却不能?
任何帮助将不胜感激。
我不知道这是否对这里有任何帮助是
program.cs
,我不知道我在这里是否犯了任何错误:
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);
}
在您的 Program.cs 中,您缺少这行代码:
app.MapControllers();
从现在开始,您的应用程序仅配置为使用最少的 api。
您始终可以使用
RouteAttribute
操作您的路线,因此控制器的基本路线是 [Route("api/[controller]")]
(如果您愿意,只能是 [Route("api")]
),这是该控制器中所有端点的基本路线。您可以在操作方法上方添加其他路线,例如 [Route("/getcopysheets")] 那么您的路线将是 http://localhost:5050/api/copysheets/getcopysheets
。
如果您对此不熟悉,我建议您深入了解文档。