我想让这个类序列化,所以我可以将它作为 httpresponsemessage 的主体发送:
[DataContract]
public class Subscription : TableServiceEntity
{
[DataMember]
public string SubscriptionId { get; set; }
[DataMember]
public bool IsAdmin { get; set; }
}
我想使用它的方式:
IList<Subscription> subs = ... ;
return new HttpResponseMessage<IList<Subscription>>(subs);
它可以编译,但是当我运行这部分时,我收到一条错误消息,指出 IList 无法序列化,我必须将其添加到已知类型集合中。我猜 TableServiceEntity 的成员不可序列化,这就是为什么我不能序列化整个列表,但我不知道如何解决这个问题。
有任何想法吗?
真挚地,
佐利
修改
正如第一条评论中所说,我添加了一个新类,它看起来像这样:
[DataServiceEntity]
[DataContract]
[KnownType(typeof(Subscription))]
public abstract class SerializableTableServiceEntity
{
[DataMember]
public string PartitionKey { get; set; }
[DataMember]
public string RowKey { get; set; }
[DataMember]
public DateTime Timestamp { get; set; }
}
[DataContract]
public class Subscription : SerializableTableServiceEntity
{
[DataMember]
public string SubscriptionId { get; set; }
[DataMember]
public bool IsAdmin { get; set; }
}
我仍然收到错误消息说
add type to known type collection and to use the serviceknowntypeattribute before the operations
我使用的唯一操作是:
public class DBModelServiceContext : TableServiceContext
{
public DBModelServiceContext(string baseAddress, StorageCredentials credentials)
: base(baseAddress, credentials) { }
public IList<Subscription> Subscriptions
{
get
{
return this.CreateQuery<Subscription>("Subscriptions").ToArray();
}
}
}
修改 2
我的界面如下所示:
[OperationContract]
[ServiceKnownType(typeof(IList<Subscription>))]
[WebGet(UriTemplate = "subscription/{value}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
HttpResponseMessage<IList<Subscription>> GetSubscription(string value);
背后的实现是:
public HttpResponseMessage<IList<Subscription>> GetSubscription(string value)
{
var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
var context = new DBModelServiceContext(account.TableEndpoint.ToString(), account.Credentials);
IList<Subscription> subs = context.Subscriptions;
return new HttpResponseMessage<IList<Subscription>>(subs);}