目录解决方案方法1使用 SchemaFilter1、创建自定义 SchemaFilter2、在 Swagger 配置中使用该 Filter方法2使用 OperationFilter 或 DocumentFilter1、创建自定义 OperationFilter2、在 Swagger 配置中使用该 Filter总结如果您喜欢此文章请收藏、点赞、评论谢谢祝您快乐每一天。在使用 Swagger 与 C# 一起工作时特别是在使用诸如 Swashbuckle.AspNetCore 这样的库时确保数据类型正确映射非常重要尤其是在处理像 long 这样的数值类型时。如果你需要将 long 类型转换为 string 类型以避免精度丢失问题你可以通过自定义 Swagger 生成逻辑来实现这一点。解决方案方法1使用 SchemaFilter你可以创建一个自定义的 ISchemaFilter 来改变属性的 Schema 类型。例如如果你想将某个 long 类型的属性转换为 string 类型可以创建一个自定义的 SchemaFilter。1、创建自定义 SchemaFilter首先创建一个实现 ISchemaFilter 的类using Swashbuckle.AspNetCore.SwaggerGen;using Microsoft.OpenApi.Models;using System.Collections.Generic;using System.Linq;public class LongToStringSchemaFilter : ISchemaFilter{public void Apply(OpenApiSchema schema, SchemaFilterContext context){if (context.Type typeof(long)){schema.Type string;schema.Format int64; // 如果需要保持数值格式可以指定为 int64}}}2、在 Swagger 配置中使用该 Filter在配置 Swagger 时使用这个过滤器services.AddSwaggerGen(c {c.SchemaFilterLongToStringSchemaFilter(); // 应用自定义过滤器// 其他配置...});方法2使用 OperationFilter 或 DocumentFilter如果你需要更细粒度的控制比如在特定操作上转换类型可以使用 OperationFilter 或 DocumentFilter。例如使用 OperationFilter1、创建自定义 OperationFilterusing Swashbuckle.AspNetCore.SwaggerGen;using Microsoft.OpenApi.Models;using System.Collections.Generic;using System.Linq;public class LongToStringOperationFilter : IOperationFilter{public void Apply(OpenApiOperation operation, OperationFilterContext context){var parametersToChange context.MethodInfo.GetParameters().Where(p p.ParameterType typeof(long)).Select(p p.Name).ToList();foreach (var param in operation.Parameters){if (parametersToChange.Contains(param.Name)){param.Schema.Type string;param.Schema.Format int64; // 如果需要保持数值格式可以指定为 int64}}}}2、在 Swagger 配置中使用该 Filterservices.AddSwaggerGen(c {c.OperationFilterLongToStringOperationFilter(); // 应用自定义过滤器// 其他配置...});总结通过上述任一方法你可以在 Swagger 中将 long 类型的参数或属性转换为 string 类型从而避免精度丢失问题。选择哪种方法取决于你的具体需求比如是否需要全局转换还是仅在特定操作上转换。如果您喜欢此文章请收藏、点赞、评论谢谢祝您快乐每一天。