相关疑难解决方法(0)

ASP.NET Core 6+ 如何在启动过程中访问配置

在早期版本中,我们有 Startup.cs 类,并在Startup文件中获取配置对象,如下所示。

public class Startup 
{
    private readonly IHostEnvironment environment;
    private readonly IConfiguration config;

    public Startup(IConfiguration configuration, IHostEnvironment environment) 
    {
        this.config = configuration;
        this.environment = environment;
    }

    public void ConfigureServices(IServiceCollection services) 
    {
        // Add Services
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
    {
        // Add Middlewares
    }

}
Run Code Online (Sandbox Code Playgroud)

现在,在 .NET 6 及更高版本(使用 Visual Studio 2022)中,我们看不到Startup.cs类。看来它的日子屈指可数了。那么我们如何获取配置(IConfiguration)和托管环境(IHostEnvironment)等对象

我们如何获取这些对象,也就是说从 appsettings 读取配置?目前,Program.cs 文件如下所示。

using Festify.Database;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

builder.Services.AddDbContext<FestifyContext>();


//////////////////////////////////////////////// …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-core .net-6.0 .net-7.0

255
推荐指数
7
解决办法
25万
查看次数

.NET 7 和 UseEndPoints()

我正在尝试将 .NET Core 3.1 项目转换为 .NET 7。

当我在课堂上使用它时Program.cs

app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();

    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});
Run Code Online (Sandbox Code Playgroud)

它给了我这样的信息:

建议使用顶级路由注册 UseEndpoints

Show potential fixes然后,我在 Visual Studio 中单击,它显示以下提示:

app.UseEndpoints(endpoints =>
{
    _ = endpoints.MapRazorPages();

    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});
Run Code Online (Sandbox Code Playgroud)

这对我来说看起来是一样的。

在.NET 7中,如果我需要使用RazorPages()该怎么办?

谢谢!

c# asp.net-core razor-pages .net-7.0 asp.net-core-7.0

25
推荐指数
1
解决办法
1万
查看次数