【问题标题】:starup file changes in Asp.net coreAsp.net core 中的启动文件更改
【发布时间】:2021-07-16 10:50:59
【问题描述】:

我正在将 .Net core web api 解决方案 2.2 升级到 3.1 我有疑问我应该在 statrup.cs 文件中使用什么 3.1

//目前我正在使用这个 公共启动(Microsoft.AspNetCore.Hosting.IHostingEnvironment env)

公共启动(Microsoft.Extensions.Hosting.IHostingEnvironment env)

【问题讨论】:

    标签: asp.net-core asp.net-core-3.1


    【解决方案1】:

    我正在将 .Net core web api 解决方案 2.2 升级到 3.1 我有疑问我应该在 statrup.cs 文件中为 3.1 使用什么

    如果您使用 the API template 创建一个新的 ASP.NET Core 3.1 API 项目,您会发现它使用下面的 Startup 类。

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
    
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }
    
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
    
            app.UseHttpsRedirection();
    
            app.UseRouting();
    
            app.UseAuthorization();
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
    

    与旧的对比一下,可以发现以下变化:

    • services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)改为services.AddControllers()

    • IHostingEnvironment 已过时,现在使用IWebHostEnvironment

    • app.UseEndpoints,使用端点路由

    【讨论】:

    • 但我的启动文件最初的代码是 public Startup(Microsoft.Extensions.Hosting.IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json ", 可选: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", 可选: true) .AddEnvironmentVariables(); this.Configuration = builder.Build(); ; }
    • public Startup(Microsoft.Extensions.Hosting.IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", 可选:true) .AddEnvironmentVariables(); this.Configuration = builder.Build(); ; }
    • 要配置配置提供程序,您可以检查:docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/…
    猜你喜欢
    • 2018-04-10
    • 2015-05-29
    • 2010-10-27
    • 1970-01-01
    • 2022-07-26
    • 2021-05-19
    • 2020-07-02
    • 2017-07-11
    • 1970-01-01
    相关资源
    最近更新 更多