WebApi中移除Swagger Post请求里的类类型属性
解决DbFirst实体作为Post请求模型时Swagger显示导航属性的问题
解决方案1:通过数据注解全局忽略导航属性
直接在实体类的导航属性上添加序列化忽略注解,让序列化组件(如Newtonsoft.Json或System.Text.Json)跳过这些属性。注意:此方法会全局生效,若其他场景(如接口返回数据)需要用到这些导航属性,需谨慎使用。
修改实体类代码:
public class CurrencyAccount : BaseEntity { [ForeignKey("CompanyId")] public int CompanyId { get; set; } public string Code { get; set; } public string Name { get; set; } public string Adress { get; set; } public string? TaxOffice { get; set; } [MaxLength(10)] public string? TaxIdNumber { get; set; } [MaxLength(11)] public string? IdentityNumber { get; set; } public string? Email { get; set; } public string? Authorizedperson { get; set; } // 添加JsonIgnore注解隐藏导航属性 [JsonIgnore] public Company? Company { get; private set; } [JsonIgnore] public List<BaBsReconciliation>? BaBsReconciliations { get; private set; } [JsonIgnore] public List<AccountReconciliation>? AccountReconciliations { get; private set; } }
- 若使用System.Text.Json,需引用
System.Text.Json.Serialization命名空间;若使用Newtonsoft.Json,需引用Newtonsoft.Json命名空间。
解决方案2:创建独立的请求DTO(推荐)
数据库实体类用于映射数据库结构,而请求模型应独立于数据库设计,通过DTO(数据传输对象)精准控制请求需要的字段,避免数据库结构变化直接影响API接口。
- 创建请求DTO类:
public class CurrencyAccountCreateDto { public int CompanyId { get; set; } public string Code { get; set; } public string Name { get; set; } public string Adress { get; set; } public string? TaxOffice { get; set; } [MaxLength(10)] public string? TaxIdNumber { get; set; } [MaxLength(11)] public string? IdentityNumber { get; set; } public string? Email { get; set; } public string? Authorizedperson { get; set; } }
- 修改API控制器方法,使用DTO作为请求参数:
[HttpPost("add")] public IActionResult Add(CurrencyAccountCreateDto dto) { // 手动将DTO映射为实体类(或使用AutoMapper简化映射) var currencyAccount = new CurrencyAccount { CompanyId = dto.CompanyId, Code = dto.Code, Name = dto.Name, Adress = dto.Adress, TaxOffice = dto.TaxOffice, TaxIdNumber = dto.TaxIdNumber, IdentityNumber = dto.IdentityNumber, Email = dto.Email, Authorizedperson = dto.Authorizedperson }; var result = _currencyAccountService.Add(currencyAccount); return result.IsSuccess ? Ok(result) : BadRequest(result.Message); }
解决方案3:通过Swagger筛选器仅在文档中隐藏属性
若不想修改实体类或创建DTO,可通过自定义Swagger筛选器,仅在Swagger文档中隐藏指定导航属性,但实际请求仍可接收这些属性(仅用于文档展示优化)。
在Program.cs中配置Swagger:
builder.Services.AddSwaggerGen(c => { c.SchemaFilter<HideNavigationPropertiesFilter>(); }); // 自定义Swagger属性筛选器 public class HideNavigationPropertiesFilter : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) { if (schema.Properties == null) return; // 指定要隐藏的导航属性名称 var navigationProps = new List<string> { "Company", "BaBsReconciliations", "AccountReconciliations" }; foreach (var propName in navigationProps) { if (schema.Properties.ContainsKey(propName)) { schema.Properties.Remove(propName); } } } }
内容的提问来源于stack exchange,提问作者hasanUtebay
相关产品推荐
相关产品推荐

