确定属性,根据用户Json.Net连载 [英] Determining properties to serialize in Json.Net based on user
问题描述
我创建一个ASP MVC的Web API。我现在要确定是什么性质连载基于做请求的用户对象。该ApiController知道用户。和基于用户I有一个返回一个字符串数组与属性名的用户有权对模型的函数。
I am creating a ASP MVC Web API. I now want to determine what properties to serialize of a object based on the user that is doing the request. The ApiController knows the user. And based on the user I have a function that returns a string array with the property names the user has rights to on the model.
我如何传递用户的ContractResolver所以它只会影响当前请求,并从其他用户无法simultanious请求?
How can I pass the user to the ContractResolver so it only affects the current request and not possible simultanious requests from other users?
推荐答案
您可以创建自定义 ContractResolver
var json = JsonConvert.SerializeObject(
new UserClass() {ID=666, Name="john", SurName="doe"},
new JsonSerializerSettings() { ContractResolver = new CustomContractResolver(new[]{"ID", "SurName"}) }
);
在这个例子中,输出JSON将只包括 ID
和姓
(不是名称
)
in this example, output json will only include ID
and SurName
(not 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();
}
}
这篇关于确定属性,根据用户Json.Net连载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!