再尝.NET7 NativeAOT
2023-11-29 本文已影响0人
ChenReal
今天迫不及地发表续集,因为上一回WebAPI项目的报错,得到了解决!废话不说,线上代码~
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseHttpsRedirection();
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast()
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = summaries[Random.Shared.Next(summaries.Length)]
})
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast");
app.Run();
public class WeatherForecast
{
public DateTime Date { get; set; }
public string Summary { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
下面开始划重点。昨天的代码因为用了record
语法糖来封装WeatherForecast
对象,结果编译成Native代码后Json序列化却不支持,引发报错。今天去掉把WeatherForecast
声明换成class再试,竟然意外获得成功!
爬出这个坑我Get到的教训是:语法糖虽好但不能多吃,尤其想玩NativeAOT的时候!