【问题标题】:Using [Serializable] with PetaPoco Entities and WebApi Issues将 [Serializable] 与 PetaPoco 实体和 WebApi 问题一起使用
【发布时间】:2016-03-21 03:35:00
【问题描述】:

我正在尝试将 [Serializable] 属性与 PetaPoco 实体一起使用,以便可以将其存储在 REDIS 缓存中。

将 [Serializable] 属性添加到 PetaPoca 实体类允许它使用 REDIS 缓存提供程序进行缓存,但随后会更改 WebAPI 将实体序列化为 JSON 的方式,这会中断。

有没有办法指定 WebAPI 如何将对象序列化为 JSON?

以下示例,具体而言,这是 DNN 的 DAL2 中并使用 DNN 的 https://github.com/davidjrh/dnn.rediscachingprovider RED​​IS 缓存提供程序。

DNN DAL2 / PetaPoco 对象:

[TableName("sbCurrencyRates")]
//setup the primary key for table
[PrimaryKey("CurrID", AutoIncrement = true)]
//configure caching using PetaPoco
[Cacheable("sbCurrencyRates", CacheItemPriority.Default, 20)]
//scope the objects to the ModuleId of a module on a page (or copy of a module on a page)

[Serializable]
public class CurrRateInfo
{
    public int CurrID { get; set; }
    public string CurrCode { get; set; }
    public double CurrRate { get; set; }
    public DateTime LastUpdate { get; set; }
}

WebApi 控制器:

public class RatesController : DnnApiController
{
    [AllowAnonymous]
    [HttpGet]
    public HttpResponseMessage GetRates()
    {
        CurrRatesController crc = new CurrRatesController();
        return Request.CreateResponse(HttpStatusCode.OK, crc.Get());
    }        
}

提前致谢。

【问题讨论】:

  • HttpGet 和 HttpPost 属性不能一起使用。

标签: c# json serialization asp.net-web-api dotnetnuke


【解决方案1】:

假设您使用的是最新版本的,那么Json.NET serializer is being used to serialize your class。默认情况下,Json.NET 忽略 [Serializable],但是可以强制它以与 BinaryFormatter 相同的方式序列化具有此属性的类型(即通过序列化它们的公共和私有 字段)将IgnoreSerializableAttribute 上的DefaultContractResolver 设置为false。事实上,asp.net 就是这样做的,它全局地改变了[Serializable] 类转换为 JSON 的方式——如您所见。

为防止这种情况,您的选择包括:

  1. 在 asp.net 中全局设置 IgnoreSerializableAttribute = true。为此,请参阅 ASP.NET Web API and [Serializable] classSetting IgnoreSerializableAttribute Globally in Json.net

  2. [JsonObject(MemberSerialization = MemberSerialization.OptOut)]标记你的班级:

    [Serializable]
    [JsonObject(MemberSerialization = MemberSerialization.OptOut)]
    public class CurrRateInfo
    {
    }
    
  3. 使用[DataContract][DataMember] 属性注释您的类。这些优先于[Serializable]

    [Serializable]
    [DataContract]
    public class CurrRateInfo
    {
        [DataMember]
        public int CurrID { get; set; }
        [DataMember]
        public string CurrCode { get; set; }
        [DataMember]
        public double CurrRate { get; set; }
        [DataMember]
        public DateTime LastUpdate { get; set; }
    }
    

    如果您不希望模型直接依赖于 Json.NET,并且不想更改 asp.net 的全局行为,请执行此操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-30
    • 2011-10-20
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多