阻止Azure TableEntity属性在MVC 4 WebAPI中序列化

Bry*_*ter 4 c# serialization azure-table-storage asp.net-mvc-4 asp.net-web-api

所以我有一个Subscription继承自Azure TableEntity类的Model ,用于WebApi Get方法,如下所示:

[HttpGet]
public IEnumerable<Subscription> Subscribers()
Run Code Online (Sandbox Code Playgroud)

在这个方法中,我Select在我的订阅者表上查询以查找所有订阅者,但我只想返回一些列(属性),如下所示:

var query = new TableQuery<Subscription>().Select(new string[] {
    "PartitionKey", 
    "RowKey", 
    "Description", 
    "Verified"
    });
Run Code Online (Sandbox Code Playgroud)

该模型的定义如下:

public class Subscription : TableEntity
{
    [Required]
    [RegularExpression(@"[\w]+",
     ErrorMessage = @"Only alphanumeric characters and underscore (_) are allowed.")]
    [Display(Name = "Application Name")]
    public string ApplicationName
    {
        get
        {
            return this.PartitionKey;
        }
        set
        {
            this.PartitionKey = value;
        }
    }

    [Required]
    [RegularExpression(@"[\w]+",
     ErrorMessage = @"Only alphanumeric characters and underscore (_) are allowed.")]
    [Display(Name = "Log Name")]
    public string LogName
    {
        get
        {
            return this.RowKey;
        }
        set
        {
            this.RowKey = value;
        }
    }

    [Required]
    [EmailAddressAttribute]
    [Display(Name = "Email Address")]
    public string EmailAddress { get; set; }

    public string Description { get; set; }

    public string SubscriberGUID { get; set; }

    public bool? Verified { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

以下是API查询的XML响应:

<ArrayOfSubscription>
    <Subscription>
        <ETag>W/"datetime'2013-03-18T08%3A54%3A32.483Z'"</ETag>
        <PartitionKey>AppName1</PartitionKey><RowKey>Log1</RowKey>
        <Timestamp>
            <d3p1:DateTime>2013-03-18T08:54:32.483Z</d3p1:DateTime>
            <d3p1:OffsetMinutes>0</d3p1:OffsetMinutes>
        </Timestamp>
        <ApplicationName>AppName1</ApplicationName>
        <Description>Desc</Description>
        <EmailAddress i:nil="true"/>
        <LogName>Log1</LogName>
        <SubscriberGUID i:nil="true"/>
        <Verified>false</Verified>
    </Subscription>
</ArrayOfSubscription>
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,该模型不仅具有一些其他属性,例如SubscriberGUID我不希望在响应中序列化(并且因为它们不在select查询中,所以它们无论如何都是null),但TableEntity本身具有这样的字段如PartitionKey,RowKey,Etag,和Timestamp其也被序列化.

如何继续使用Azure表,但避免在响应中序列化这些我不希望用户看到的不需要的字段.

Ric*_*uer 6

不同意使用特定DTO的答案,但Microsoft.WindowsAzure.Storage程序集现在提供了一个属性,IgnorePropertyAttribute您可以使用它来装饰公共属性以避免序列化.

我还没有真正尝试过但是有一个TableEntity被调用的方法ShouldSkipProperty()在返回之前检查了很多东西false(即不要跳过):

  • 属性名称是"PartitionKey","RowKey","Timestamp"还是"ETag" - > skip
  • 对于getter和setter是非公开的 - >跳过
  • 它是静态的 - >跳过
  • 该属性是否具有属性IgnorePropertyAttribute - > skip

看起来它会做的伎俩.