Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/36.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
C# 基于身份验证的DTO序列化_C#_Asp.net_Asp.net Web Api_Asp.net Web Api2 - Fatal编程技术网

C# 基于身份验证的DTO序列化

C# 基于身份验证的DTO序列化,c#,asp.net,asp.net-web-api,asp.net-web-api2,C#,Asp.net,Asp.net Web Api,Asp.net Web Api2,我的Web API控制器应该根据用户试图获取的模型是否属于他而返回不同的模型 例如: class Customer { public string Id { get; set; } public int UserId { get; set; } public string Name { get; set; } public decimal Revenue { get; set; } } 相应的操作将是Api/Customers/1 现在,如果该模型属于当前

我的Web API控制器应该根据用户试图获取的模型是否属于他而返回不同的模型

例如:

class Customer {
    public string Id { get; set; }

    public int UserId { get; set; }

    public string Name { get; set; }

    public decimal Revenue { get; set; }
}
相应的操作将是
Api/Customers/1

现在,如果该模型属于当前调用该操作的用户,我将返回所有字段。但是,如果其他人调用相同的操作,他应该只看到
Id
Name
字段

我知道您可以返回一个接口并根据身份验证级别选择实现,但我想知道是否有更简单的方法,如
[JsonIgnore]
但基于访问级别来实现相同的功能?它还可以帮助我减少代码重复


实现我的目标最优雅的方式是什么?

我认为可以使用JSON.NET的条件序列化(如果您使用的是JSON.NET)。这可以帮助你更多

To conditionally serialize a property add a boolean method with the same name as 
the property and then prefixed the method name with ShouldSerialize. 
The result of the method determines whether the property is serialized. 
If the method returns true then the property will be serialized, if it returns false
and the property will be skipped.

我能想到的另一件事是重写类中的Object.ToString()方法,它将根据需要返回JSON。您仍然需要指定条件,并根据条件返回您选择的JSON字符串。

太好了!我不知道条件序列化,这正是我需要的。非常感谢。