gpt4 book ai didi

How to use Program.cs file in .NET 6(如何在.NET 6中使用Program.cs文件)

转载 作者:bug小助手 更新时间:2023-10-28 21:06:28 28 4
gpt4 key购买 nike



In the latest version of .Net the Startup class and Program class are merged together and the using and other statements are simplified and removed from Program.cs. I am really confused about how to use it all in one file.
Please help me to migrate all services to the program.cs file.

在最新版本的.Net中,Startup类和Program类合并在一起,using和其他语句被简化并从Program.cs中删除。我真的很困惑如何在一个文件中使用它。请帮助我将所有服务迁移到program.cs文件。


Startup.cs file :

Startup.cs文件:


public class Startup
{
private readonly IConfigurationRoot configRoot;
private AppSettings AppSettings { get; set; }

public Startup(IConfiguration configuration)
{
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
Configuration = configuration;

IConfigurationBuilder builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
configRoot = builder.Build();

AppSettings = new AppSettings();
Configuration.Bind(AppSettings);
}

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
services.AddController();

services.AddDbContext(Configuration, configRoot);

services.AddIdentityService(Configuration);

services.AddAutoMapper();

services.AddScopedServices();

services.AddTransientServices();

services.AddSwaggerOpenAPI();

services.AddMailSetting(Configuration);

services.AddServiceLayer();

services.AddVersion();

services.AddHealthCheck(AppSettings, Configuration);

services.AddFeatureManagement();
}



public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory log)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseCors(options =>
options.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod());

app.ConfigureCustomExceptionMiddleware();

log.AddSerilog();

//app.ConfigureHealthCheck();


app.UseRouting();

app.UseAuthentication();

app.UseAuthorization();
app.ConfigureSwagger();
app.UseHealthChecks("/healthz", new HealthCheckOptions
{
Predicate = _ => true,
ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse,
ResultStatusCodes =
{
[HealthStatus.Healthy] = StatusCodes.Status200OK,
[HealthStatus.Degraded] = StatusCodes.Status500InternalServerError,
[HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable,
},
}).UseHealthChecksUI(setup =>
{
setup.ApiPath = "/healthcheck";
setup.UIPath = "/healthcheck-ui";
//setup.AddCustomStylesheet("Customization/custom.css");
});


app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}

Program.cs file :

Program.cs文件:


 public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}

更多回答

"In the latest version of .Net the Startup class and Program class are merged together" <-- uuuhh, this isn't exactly true

“在最新版本的.NET中,Startup类和Program类合并在一起”<--uuuhh,这并不完全正确

You can still keep everything as it is, just change framework to <TargetFramework>net6.0</TargetFramework> and update all packages

您仍然可以保持一切原样,只需将框架更改为net6.0并更新所有包

@Dai Isn't it? Because the Microsoft documentation article What's new in ASP.NET Core 6.0 does mention that: The web app templates: Unifies Startup.cs and Program.cs into a single Program.cs file.

@戴是不是?因为Microsoft文档文章What's new in ASP.NET Core 6.0确实提到:Web应用程序模板:将Startup.cs和Program.cs统一到单个Program.cs文件中。

Yeah, the TEMPLATE.

是的,模板。

优秀答案推荐

You modify your csproj file

您可以修改csproj文件


<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>


The new template get rid of a lot of boilerplate code. Here is the example according to the MS documentation.

新的模板去掉了许多样板代码。以下是根据MS文档提供的示例。


var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();

// The production configuration
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}

// Configure the application
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();

app.Run();

The advantage is that it achieves the same thing in less code. It is more readable, however a migration should be taken manually.

其优势在于,它用更少的代码实现了相同的功能。它的可读性更好,但是应该手动进行迁移。


Or maybe someone came up with some smart migration script? I am not aware of any migration or "program-and-startup-class merger" script, yet.

或者,也许有人想出了一些聪明的迁移脚本?我还没有意识到有任何迁移或“项目和初创企业类合并”的脚本。


更多回答

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com