CloudYxt.MinimalApi.OpenApi 1.0.0

dotnet add package CloudYxt.MinimalApi.OpenApi --version 1.0.0
                    
NuGet\Install-Package CloudYxt.MinimalApi.OpenApi -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="CloudYxt.MinimalApi.OpenApi" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CloudYxt.MinimalApi.OpenApi" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="CloudYxt.MinimalApi.OpenApi" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add CloudYxt.MinimalApi.OpenApi --version 1.0.0
                    
#r "nuget: CloudYxt.MinimalApi.OpenApi, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#addin nuget:?package=CloudYxt.MinimalApi.OpenApi&version=1.0.0
                    
Install CloudYxt.MinimalApi.OpenApi as a Cake Addin
#tool nuget:?package=CloudYxt.MinimalApi.OpenApi&version=1.0.0
                    
Install CloudYxt.MinimalApi.OpenApi as a Cake Tool

云享通.Net Core针对MinimalApi常规操作库,同时整合扩展Microsoft.AspNetCore.OpenApi

以Program.cs为例的使用方法

#pragma warning disable IL2026, IL3050
//AOT编译需要的JSON序列化类型
AppJsonSerializer.TypeInfoResolver = AppJsonSerializerContext.Default;

ApiMessageLogFilter.ApiName = "testApi";
//日志回调处理
ApiMessageLogFilter.CallBack = (log) =>
{
    Console.WriteLine("---------");
    Console.WriteLine(JsonSerializer.Serialize(log, AppJsonSerializer.JsonOptions));
};

//用户认证方法,认证成功时返回用户对象
ApiMessageAuthorizationFilter.ApiAuthorization = (policy, roles, authSchemes, context, scheme, param) =>
{
    if (param != "expected-token")
        throw new ApiMessageException(403, "无效令牌");

    return new { id = "admin" };
};
#pragma warning restore IL2026, IL3050

var builder = WebApplication.CreateSlimBuilder(args);
builder.WebHost.UseUrls("http://*:5004");
builder.Services.ConfigureHttpJsonOptions(options =>
{
    //注册AOT编译需要的JSON序列化类型
    options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializer.TypeInfoResolver);
});

//注册OpenApi
builder.Services.AddOpenApi("demoApi", options =>
{
    options.AddDocumentTransformer((document, context, cancellationToken) =>
    {
        document.Info.Title = "demoApi";
        document.Info.Contact = new OpenApiContact
        {
            Name = "CloudYxt Support",
            Email = "support@cloudyxt.com"
        };
        return Task.CompletedTask;
    });

    //添加ApiMessageAuthorization加锁支持
    options.AddApiMessageAuthorizationSupport();
});

var app = builder.Build();
//全局错误输出的包装方式,现已有四种包装模式
app.UseExceptionHandler(ExceptionHandlers.HandleGlobalToCodeMessage);
//app.UseExceptionHandler(ExceptionHandlers.HandleGlobalToMessageInfo);
//app.UseExceptionHandler(ExceptionHandlers.HandleGlobalToStatusMessage);
//app.UseExceptionHandler(ExceptionHandlers.HandleGlobalToStatusMessageData);

//定义最基本的api过滤器绑定(注意:过滤器的顺序)
var api = app.MapGroup("/")
    //日志过滤器
    .AddEndpointFilter<ApiMessageLogFilter>()
    //将错误输出的包装方式
    .AddEndpointFilter<PackProblemToCodeMessageFilter>()
    //捕获API中的throw new ApiMessageException(10, "错误");
    .AddEndpointFilter<ApiMessageExceptionFilter>();

//GET的参数验证
api.MapGet("/authget", ([AsParameters] request_authget request) => $"auth get id:{request.id}")
    //使用的验证
    .WithValidationFilter<request_authget>();

//POST的参数验证
api.MapPost("/authpost", ([Description("The name of the person to greet.")] request_auth request) =>
    {
        if (request.name == "err")
            throw new ApiMessageException(10, "错误");

        return Results.Content($"authpost:{request.name}");
    })

    //若需忽略错误包装
    //.WithMetadata(new PackProblemIgnoreAttribute())
    //若需忽略用户验证
    //.WithMetadata(new AllowAnonymousAttribute())

    //用户认证处理
    //验证用户
    .WithApiMessageAuthorization()
    //自定义验证用户
    .WithApiMessageAuthorization(policy: "", schemes: "Bearer,Auth", roles: "0,1")

    //模型验证处理
    .WithValidationFilter<request_auth>();

//设置OpenApi文档的json生成地址(此处最终生成到“/demoApi/demoApi.json”)
app.MapOpenApi("/demoApi/{documentName}.json");

app.Run();

public class request_authget
{
    [Required]
    public string id { get; set; }

    [Range(1, 2)]
    public int num { get; set; }
}

public class request_auth
{
    public int id { get; set; }
    [Required(ErrorMessage = "名称必须填写")]
    public string name { get; set; }
}

//AOT需要的模型的JSON序列化扩展
[JsonSerializable(typeof(request_auth))]
[JsonSerializable(typeof(request_authget))]
internal partial class AppJsonSerializerContext : JsonSerializerContext
{

}

跨域中间件使用

在Startup的Configure中定义

//支持所有域
app.UseMiddleware<AllowDomainCorsHeaderMiddleware>();

//支持一个域名跨域
app.UseMiddleware<AllowDomainCorsHeaderMiddleware>("https://www.domain1.com");

//支持多个域名跨域
app.UseMiddleware<AllowDomainCorsHeaderMiddleware>("https://www.domain1.com,https://www.domain2.com");

基于HttpContext的扩展

var ip = HttpContext.remoteRealIp(); //来源IP
var from = HttpContext.remoteFrom(); //来源URL
var agent = HttpContext.remoteAgent(); //来源AGENT
Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.0.0 148 4/25/2025

云享通.Net Core针对MinimalApi常规操作库,详细使用请常见README.md