【问题标题】:How can we hide a property in WebAPI?我们如何在 WebAPI 中隐藏属性?
【发布时间】:2020-07-15 03:00:03
【问题描述】:

我有一个模特说下

public class Device
{        
        public int DeviceId { get; set; }
        public string DeviceTokenIds { get; set; }
        public byte[] Data { get; set; }
        public string FilePwd { get; set; }        
}

现在我有一个 ASP.net Web API,其中有一个 POST 方法,如下所示

[HttpPost]
[Route("AddDeviceRegistrations")]
public void InsertDeviceRegistrations(Device device)

如果我公开 WebAPI,显然所有字段都将可用,例如

{
  "DeviceId": 1,
  "DeviceTokenIds": "sample string 2",
  "Data": "QEBA",
  "FilePwd": "sample string 3"
}

我想要的是,每当我公开我的 WebAPI 时,DeviceID 都不应该公开。我的意思是我正在寻找

{

      "DeviceTokenIds": "sample string 2",
      "Data": "QEBA",
      "FilePwd": "sample string 3"
}

有可能吗?如果有怎么办?

我可以通过将函数签名更改为来解决问题

public void InsertDeviceRegistrations(string deviceTokenIds, byte[] data, string FilePwd).

但我想知道这是否可能? 如果有,怎么做?

提前致谢。

【问题讨论】:

标签: c# asp.net-web-api


【解决方案1】:

我才发现

[IgnoreDataMember]
 public int DeviceId { get; set; }

命名空间是System.Runtime.Serialization

更多信息IgnoreDataMemberAttribute Class

今天学到了一些新东西。

谢谢大家。

【讨论】:

  • 完美答案!
  • 这可行,但如果您使用相同的数据模型进行 GET 操作,这些字段将丢失。
【解决方案2】:

对所有 GET/POST 请求使用视图模型是一种很好的做法。 在您的情况下,您应该创建用于在 POST 中接收数据的类:

public class InsertDeviceViewModel
{        
    public string DeviceTokenIds { get; set; }
    public byte[] Data { get; set; }
    public string FilePwd { get; set; }        
}

然后将数据从视图模型映射到您的业务模型Device

【讨论】:

    【解决方案3】:

    如果您使用的是Newtonsoft.Json

    你可以像这样隐藏属性:

    public class Product
    {
        [JsonIgnore]
        public string internalID { get; set; };
        public string sku { get; set; };
        public string productName { get; set; };
    }
    

    您的序列化响应将不包含 internalID 属性。

    【讨论】:

      【解决方案4】:

      在属性顶部使用属性 [NonSerialized] 会阻止其在输出 JSON/XML 中被序列化。

      public class Device
      {        
              [NonSerialized]
              public int DeviceId { get; set; }
      
              public string DeviceTokenIds { get; set; }
              public byte[] Data { get; set; }
              public string FilePwd { get; set; }        
      }
      

      【讨论】:

      • 嗨,我刚刚发现 [IgnoreDataMember]
      【解决方案5】:

      如果你想隐藏带有空参数的 Resonse 类的数据成员。转到位于 App_start 文件夹中的项目 WebApiConfig 文件,添加以下代码:

      var jsonConfig = config.Formatters.JsonFormatter;
      jsonConfig.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
      

      【讨论】:

        猜你喜欢
        • 2023-03-19
        • 2016-09-25
        • 1970-01-01
        • 1970-01-01
        • 2018-07-08
        • 2014-07-05
        • 1970-01-01
        • 2010-10-23
        • 1970-01-01
        相关资源
        最近更新 更多