从 swagger 响应中排除 ef 虚拟属性

Tob*_*bol 5 c# swagger swashbuckle asp.net-core-webapi

我使用 ef-core 将 Swashbuckle 添加到了 .net core web-api 项目。我的问题是我的 ef 自动生成的类的虚拟属性被添加到 swagger 示例响应中,这使得响应变得巨大,我只想显示表属性,而不是关系。

控制器的代码示例:

[HttpGet("devices", Name = "GetDevices")]
public async Task<ActionResult<List<Device>>> Devices()
{
    var devices = await _deviceDa.GetDevices();
    return Json(devices);
}
Run Code Online (Sandbox Code Playgroud)

我的问题是 ef 自动生成的类位于一个单独的类库中,我无权更改。我不能简单地将 JsonIgnore 添加到这些虚拟属性中。

是否有可能让 Swashbuckle 忽略所有虚拟属性?

Tao*_*hou 3

您可以实现自己的模型ContractResolver,以在序列化模型时忽略虚拟属性。

  1. IgnoreVirtualContractResolver

    public class IgnoreVirtualContractResolver: DefaultContractResolver
    {
        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            JsonProperty prop = base.CreateProperty(member, memberSerialization);
            var propInfo = member as PropertyInfo;
            if (propInfo != null)
            {
                if (propInfo.GetMethod.IsVirtual && !propInfo.GetMethod.IsFinal)
                {
                    prop.ShouldSerialize = obj => false;
                }
            }
            return prop;
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 登记

    services.AddMvc()
            .AddJsonOptions(options => {
                options.SerializerSettings.ContractResolver = new IgnoreVirtualContractResolver();
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    
    Run Code Online (Sandbox Code Playgroud)