在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
介绍vs2022正式版已经推出了,估计很多人已经下载并开始创建.Net 6 开始尝鲜了, 本节我简要的给大家介绍一下.Net 6的一些改动。 正文本次.Net6带来最明显的变化就是:
var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.Run(); 对于这样的改动大家可能会觉得这是C# 10 带来的优化,但我的理解是.Net6为了新手更加方便入门,早期我们使用.Net Core 2/3/5 版本,还要给新人解释系统启动入口 我们来看一下之前的语法,我们有一大堆嵌套的 lambda,代码看上去非常复杂。 var hostBuilder = Host.CreateDefaultBuilder(args) .ConfigureServices(services => { services.AddControllers(); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.Configure((ctx, app) => { if (ctx.HostingEnvironment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", () => "Hello World!"); endpoints.MapRazorPages(); }); }); }); hostBuilder.Build().Run(); 升级到.Net 6之后,我们可以使用更简单的 API 来实现。 var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); var app = builder.Build(); app.MapGet("/", () => "Hello World!"); app.Run(); 对比我们将 2个版本的语法对比来看 向DI 容器添加服务var hostBuilder = Host.CreateDefaultBuilder(args); hostBuilder.ConfigureServices(services => { services.AddControllers(); services.AddSingleton<MyThingy>(); }) var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddSingleton<MyThingy>(); 日志记录var hostBuilder = Host.CreateDefaultBuilder(args); hostBuilder.ConfigureLogging(builder => { builder.AddFile(); }) var builder = WebApplication.CreateBuilder(args); builder.Logging.AddFile(); Serilog 集成public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseSerilog() // <-- Add this line .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); builder.Host.UseSerilog(); 完成的来看效果public interface IHelloService { string Hello(bool isHappy); } public class HelloService : IHelloService { public string Hello(bool isHappy) { var hello = $"Hello World"; if (isHappy) return $"{hello}, you seem to be happy today"; return hello; } } using MinimalApiDemo; using System.Security.Claims; var builder = WebApplication.CreateBuilder(args); builder.Services.AddScoped<IHelloService, HelloService>(); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.MapGet("/Hello", (bool? isHappy, IHelloService service) => { if (isHappy is null) return Results.BadRequest("Please tell if you are happy or not :-)"); return Results.Ok(service.Hello((bool)isHappy)); }); app.Run(); 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持极客世界。 |
请发表评论