有没有办法在不使用注释的情况下忽略类属性

时间:2016-02-01 12:01:54

标签: c# asp.net asp.net-mvc asp.net-web-api2

以下是返回Agent对象的api调用

[Route("GetAgentById")]
    public Agent GetAgentById(int id)
    {
        //Restrict Class fields
        return new Agent(id);
    }

代理类有很多字段(比方说100个字段)

 public class Agent
  {       
    public int AgentId { get; set; }
    public string AgentName { get; set; }
    public bool IsAssigned { get; set; }
    public bool IsLoggedIn { get; set; }
    ......
    ......
    public Agent() { }
 }

有没有办法在不使用注释的情况下忽略类属性。我只想在从api调用返回代理对象之前返回代理对象的一些字段。有没有办法做到这一点

1 个答案:

答案 0 :(得分:0)

返回只包含必需属性的匿名对象,例如:

return new { agent.AgentId, agent.AgentName } 

或使用DTO(在架构上更正确,特别是如果您正在构建复杂的解决方案),在此示例中使用Automapper

return Mapper.Map<AgentDTO>(agent); 

但是如果你真的想使用“选择退出”方法并序列化你的对象的小部分,并且如果你使用的是JSON.NET,你可以只标记需要序列化的属性:

[DataContract]
public class Agent
{       
  // included in JSON
  [DataMember]
  public int AgentId { get; set; }
  [DataMember]
  public string AgentName { get; set; }

  // ignored
  public bool IsAssigned { get; set; }
  public bool IsLoggedIn { get; set; }  
}
相关问题