裁剪减小体积,取消JIT编译,不使用反射技术。直接产生目标机器二进制代码,目前支持x86,解决被反编译问题。
使用CreateSlimBuilder()模式
var builder = WebApplication.CreateSlimBuilder();
builder.Services.AddRoutingCore().Configure<RouteOptions>(options => {
options.SetParameterPolicy<RegexInlineRouteConstraint>("regex");
});
OpenAPI基于IEndpointRouteBuilder扩展方法创建MapGet、MapPost等来实现EndPoints
namespace Microsoft.AspNetCore.Builder
{
//
// 摘要:
// Provides extension methods for Microsoft.AspNetCore.Routing.IEndpointRouteBuilder
// to add endpoints.
public static class EndpointRouteBuilderExtensions
{
public static RouteHandlerBuilder MapDelete(this IEndpointRouteBuilder endpoints, [StringSyntax("Route")] string pattern, Delegate handler);
...
}}
在NET8的 AoT编译中不支持反射技术,对于Json序列化使用源生成器方式构建。
[JsonSerializable(typeof(WeatherForecast), GenerationMode = JsonSourceGenerationMode.Metadata)]
internal partial class MetadataOnlyWeatherForecastOnlyContext : JsonSerializerContext
{
}
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolverChain.Insert(0, Device_ProjectJsonSerializerContext.Default);
});
JsonSerializer.Serialize(reponse, Device_Model_Product_AssetsJsonSerializerContext.Default.APIResponseDevice_Model_Product_Assets)
通过基于扩展WebApplication从而创建OpenAPI, 在Program中使用 app.MapProjectEndpoints();和builder.Services.AddTransient<ProductService>();注入Endpoint组件和Services组件来解耦。
public static class ProductEndpoints
{
public static void MapProductEndpoints(this WebApplication app)
{
var api = app.MapGroup("/api");
var productApi = api.MapGroup("/product").WithGroupName("产品");
productApi.MapGet("/list", (ProductService service) =>
{
return Results.Text(JsonSerializer.Serialize(new APIResponse<Device_Product> { Data = service.GetProductToList() }, Device_ProductJsonSerializerContext.Default.APIResponseDevice_Product));
});
}
}
public class ProductService
{
public List<Device_Product> GetProductToList()
{
return DBContext.DB.Queryable<Device_Product>().ToList();
}
}
<Directives>
<Application>
<Assembly Name="SqlSugar" Dynamic="Required All">
</Assembly>
<Assembly Name="OpenAPIServices" Dynamic="Required All">
</Assembly>
</Application>
</Directives>