【发布时间】:2021-09-15 21:44:14
【问题描述】:
如何将我的“/api/employees”路由移出 program.cs?
程序.cs:
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("AppDb");
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlServer(connectionString));
builder.Services.AddAuthorization();
builder.Services.AddAuthentication();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (builder.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.UseAuthentication();
app.MapControllers();
app.MapGet("/", () => "Hello World!");
app.Run();
我见过微软的人做这样的事情:
public class EmployeeApi
{
public static void MapRoutes(IEndpointRouteBuilder routes)
{
routes.MapGet("/api/employees", async ([FromServices] AppDbContext db) =>
{
return await db.Employees.ToListAsync();
});
routes.MapGet("api/employees/{id}", async (int id, [FromServices] AppDbContext db) =>
{
return await db.Employees.FindAsync(id);
});
}
}
他们创建了一个新班级。但我不知道如何实现这一点,以便程序知道这些路由存在。
【问题讨论】:
标签: c# .net asp.net-core .net-6.0