我正在创建一个ASP MVC Web API。我现在想要根据执行请求的用户确定要对象序列化的属性。 ApiController知道用户。基于用户,我有一个函数返回一个字符串数组,其中包含用户对模型有权限的属性名称。
如何将用户传递给ContractResolver,以便它只影响当前请求而不会影响其他用户的同步请求?
答案 0 :(得分:5)
您可以创建自定义ContractResolver
var json = JsonConvert.SerializeObject(
new UserClass() {ID=666, Name="john", SurName="doe"},
new JsonSerializerSettings() { ContractResolver = new CustomContractResolver(new[]{"ID", "SurName"}) }
);
在此示例中,输出json将仅包含ID
和SurName
(不是Name
)
public class UserClass
{
public int ID { set; get; }
public string Name {set; get;}
public string SurName { set; get; }
}
public class CustomContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
{
IEnumerable<string> _allowedProps = null;
public CustomContractResolver(IEnumerable<string> allowedProps)
{
_allowedProps = allowedProps;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
return _allowedProps.Select(p=>new JsonProperty() {
PropertyName = p,
PropertyType = type.GetProperty(p).PropertyType,
Readable = true,
Writable = true,
ValueProvider = base.CreateMemberValueProvider(type.GetMember(p).First())
} ).ToList();
}
}
答案 1 :(得分:1)
您是否无法为api收到的每个请求创建新的合约解析程序? 只要您为每个请求创建一个新实例,合同解析器就永远不会相互冲突 代码可能如下所示:
var resolver = new MyUserBasedResolver(userObject);
JsonConvert.SerializeObject(
product,
Formatting.Indented,
new JsonSerializerSettings { ContractResolver = resolver }
);