Cha*_*max 2 .net c# asp.net-core .net-6.0
如何将“/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();
Run Code Online (Sandbox Code Playgroud)
我见过微软的人做了这样的事情:
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);
});
}
}
Run Code Online (Sandbox Code Playgroud)
他们创建了一个新班级。但我不知道如何实现这一点,以便程序知道这些路由的存在。
您可以创建一个扩展方法并在文件中调用它program.cs:
public static class EmployeeApi
{
public static void MapEmployeesRoutes(this IEndpointRouteBuilder app)
{
app.MapGet("/api/employees", async ([FromServices] AppDbContext db) =>
{
return await db.Employees.ToListAsync();
});
app.MapGet("api/employees/{id}", async (int id, [FromServices] AppDbContext db) =>
{
return await db.Employees.FindAsync(id);
});
}
}
Run Code Online (Sandbox Code Playgroud)
并在您的program.cs文件中调用您的方法:
app.MapGet("/", () => "Hello World!");
app.MapEmployeesRoutes();
Run Code Online (Sandbox Code Playgroud)
你的program.cs文件应该是这样的:
app.MapGet("/", () => "Hello World!");
app.MapEmployeesRoutes();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4168 次 |
| 最近记录: |