c# - 根据用户确定在 Json.Net 中序列化的属性

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

我正在创建一个 ASP MVC Web API。我现在想根据执行请求的用户确定要序列化对象的哪些属性。 ApiController 知道用户。基于用户,我有一个函数返回一个字符串数组,其中包含用户在模型上有权访问的属性名称。

如何将用户传递给 ContractResolver,使其仅影响当前请求,而不会影响其他用户的同时请求?

最佳答案

您可以创建自定义ContractResolver

var json = JsonConvert.SerializeObject(
                new UserClass() {ID=666, Name="john", SurName="doe"},
                new JsonSerializerSettings() { ContractResolver = new CustomContractResolver(new[]{"ID", "SurName"}) }
            );

在此示例中,输出 json 将仅包含 IDSurName(不包含 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();
    }
}

关于c# - 根据用户确定在 Json.Net 中序列化的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22042306/

相关文章:

c# - 如何将一个数组项属性值设置为对另一个项的引用的 C# 数组转换为 JSON

c# - 如何将我的 .net WinForms 应用程序转换为 Windows 10 Mobile?

mysql - linq 中的 Intersect 或 Except 方法在 MYSQL 中不起作用

c# - 如何在 websocket 请求期间验证 JWT。 .net核心

asp.net-mvc-4 - ASP.Net MVC 4 WebAPI POST 返回 404

c# - Newtonsoft 与 IDynamicMetaObjectProvider 实现反序列化类相关的问题

c# - 查找多个元素并根据结果设置属性

c# - 如何从非托管 C++ 使用进程内 WCF 服务

c# - 具有相同 URL 路由但不同 HTTP 方法的多个 Controller

c# - 使用 JSON.NET 将子数据集合反序列化为 ienumerables