Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/google-chrome/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net web api 使用属性对属性进行Web API条件序列化_Asp.net Web Api - Fatal编程技术网

Asp.net web api 使用属性对属性进行Web API条件序列化

Asp.net web api 使用属性对属性进行Web API条件序列化,asp.net-web-api,Asp.net Web Api,如何根据用户角色使用属性从WEB API响应中包括/排除属性?例如: public class Employee { public string FullName { get; set;} [DataMember(Role="SystemAdmin")] // included only for SystemAdmins public string SSN { get; set; } } 根据在web api中使用的序列化程序,可以使用条件序列化 如果您只是从We

如何根据用户角色使用属性从WEB API响应中包括/排除属性?例如:

public class Employee 
{ 
    public string FullName { get; set;}

    [DataMember(Role="SystemAdmin")] // included only for SystemAdmins
    public string SSN { get; set; }
}

根据在web api中使用的序列化程序,可以使用条件序列化

如果您只是从Web API返回JSON,那么它很简单——我只使用JSON序列化程序,这个解决方案适合我。默认情况下,Web API使用JSON.Net进行JSON序列化。您可以添加一个ShouldSerialize方法,该方法返回bool。在“应序列化”中,可以测试用户是否为InRole

public class Employee
{
   public string Name { get; set; }
   public string Manager { get; set; }

   public bool ShouldSerializeManager()
   {
    // don't serialize the Manager property for anyone other than Bob..
    return (Name == "Bob");
   }
}

更多

在使用JSON.NETWebAPI序列化时,[JsonIgnore]属性要么全是,要么全是

其他序列化程序需要不同的方法

XmlSerializer也支持这一点,但必须启用它

config.Formatters.XmlFormatter.UseXmlSerializer = true;  
datacontract序列化程序是默认的

如果使用此选项,则必须将逻辑添加到属性中,如果为null,则忽略它们。。如果在其他地方使用该类,这可能是一个问题。[IgnoreDataMember]属性为全部或无

[DataContract]
public class Person
{
  private string firstName;
  [DataMember(IsRequired = false, EmitDefaultValue = false)]
  public string FirstName
  {
    get
    {
        //Put here any condition for serializing
        return string.IsNullOrWhiteSpace(firstName) ? null : firstName;
    }
    set
    {
        firstName = value;
    }
  }
}

谢谢你的回答。我知道JSON.Net的ShouldSerialize[PropertyName]方法,但是我希望使用属性,以避免在属性名称更改时必须重命名ShouldSerialize方法。ShouldSerialize方法容易拼写错误和被忽略,因此,如果不小心,属性可能会被序列化,应该从响应中排除。我将投票表决这个答案,但这不是我所希望的答案