ABP VNext + .NET Minimal API:极简微服务快速开发

ABP VNext + .NET Minimal API:极简微服务快速开发 💨



1. 引言 🚀

TL;DR ✨

  • 🔥 极简上手:用 .NET Minimal API + ABP VNext,仅需一个 Program.cs 即可启动轻量级微服务
  • 🛡️ 保留核心能力:依然拥有 ABP 的依赖注入(DI)、AOP 拦截器、配置管理、审计日志等特性
  • 🎉 即开即用:ProblemDetails 异常格式、Swagger/OpenAPI、多版本 API 文档、API 版本管理、健康检查、CORS、多语言本地化一键配置
  • 高性能、高可用:Serilog 日志 + Kestrel 原生优化 + Docker Compose,启动秒级响应

2. 环境与依赖 🛠️

  • .NET SDK:6 +

  • ABP VNext:6.x +

  • 数据库:PostgreSQL(生产)、In-Memory(测试)

  • 关键 NuGet 包

    dotnet add package Volo.Abp.AspNetCore.Builder  
    dotnet add package Volo.Abp.Modularity  
    dotnet add package Volo.Abp.EntityFrameworkCore.PostgreSql  
    dotnet add package Volo.Abp.AutoMapper  
    dotnet add package Volo.Abp.AspNetCore.Serilog        # Serilog 丰富器  
    dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer  
    dotnet add package Swashbuckle.AspNetCore  
    dotnet add package Asp.Versioning.Http  
    dotnet add package Asp.Versioning.Mvc.ApiExplorer      # 版本化 ApiExplorer  
    dotnet add package Hellang.Middleware.ProblemDetails    # ProblemDetails 中间件  
    dotnet add package Serilog  
    dotnet add package Serilog.Sinks.Console               # Serilog 控制台 Sink  
    dotnet add package StackExchange.Redis  
    

3. 项目结构与入口 📂

MyMinimalService/
├─ Program.cs
├─ Modules/
│    └─ MyServiceModule.cs
├─ Application/
│    ├─ Dtos/
│    │    ├─ UserDto.cs
│    │    └─ CreateUserDto.cs
│    └─ IUserAppService.cs
├─ Domain/
│    ├─ Entities/
│    │    └─ User.cs
│    └─ MyDbContext.cs
└─ appsettings.json

4. Program.cs 📝

using System.Text.Json;
using System.Text.Json.Serialization;
using Hellang.Middleware.ProblemDetails;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.Versioning;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using Serilog;
using Volo.Abp;
using Volo.Abp.Autofac;
using Volo.Abp.AspNetCore.Builder;     // 确保 AddApplication 扩展可用
using Volo.Abp.AspNetCore.Serilog;
using Volo.Abp.EventBus;                // 确保 AddAbpEventBus 扩展可用
using Volo.Abp.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// 1. Serilog 全局配置 🔥
builder.Host.UseSerilog((ctx, lc) =>
{
   
   
    lc.ReadFrom.Configuration(ctx.Configuration)
      .Enrich.FromLogContext()
      .Enrich.WithProperty("Application", ctx.HostingEnvironment.ApplicationName)
      .WriteTo.Console();
});

// 2. 使用 Autofac 容器,确保 ABP AOP 拦截器生效 🛡️
builder.Host.UseAutofac();

// 3. 注册 ABP 模块化支持(包含 ASP.NET Core 特性)📦
builder.Services.AddApplication<MyServiceModule>();

// 4. 本地化:资源文件路径 🌐
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

// 5. ProblemDetails 异常格式化 ⚠️
builder.Services.AddProblemDetails(opts =>
{
   
   
    opts.MapToStatusCode<Exception>(StatusCodes.Status500InternalServerError);
});

// 6. 身份验证与授权 🔒
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options => {
   
   
        options.Authority = builder.Configuration["Auth:Issuer"];
        options.Audience  = builder.Configuration["Auth:Audience"];
    });
builder.Services.AddAuthorization();

// 7. 启用 ABP 事件总线(自动注册 AOP 拦截器)🔄
builder.Services.AddAbpEventBus();

// 8. JSON 序列化优化 📲
builder.Services.Configure<JsonOptions>(opts =>
{
   
   
    opts.SerializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
    opts.SerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});

// 9. API 版本化 📑
builder.Services.AddApiVersioning(opts =>
{
   
   
    opts.AssumeDefaultVersionWhenUnspecified = true;
    opts.DefaultApiVersion = new ApiVersion(1, 0);
    opts.ReportApiVersions = true;
    opts.ApiVersionReader = new UrlSegmentApiVersionReader();
});
builder.Services.AddVersionedApiExplorer(opts =>
{
   
   
    opts.GroupNameFormat = "'v'VVV";
    opts.SubstituteApiVersionInUrl = true;
});

// 10. Swagger/OpenAPI 🛠️
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(opts =>
{
   
   
    // 在此阶段 BuildServiceProvider 有轻微容器重复,但示例中可用
    var provider = builder.Services.BuildServiceProvider()
                        .GetRequiredService<IApiVersionDescriptionProvider>();
    foreach (var desc in provider.ApiVersionDescriptions)
    {
   
   
        opts.SwaggerDoc(desc.GroupName, new OpenApiInfo {
   
   
            Title   = "MyMinimalService",
            Version = desc.ApiVersion.ToString()
        }
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kookoos

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值