【问题标题】:How to ensure correct encoding in OData v4 Dynamic Properties如何确保在 OData v4 动态属性中正确编码
【发布时间】:2019-03-25 13:21:24
【问题描述】:

我正在使用最新的 OData NuGet 包编写 OData V4 服务/Web API 2。我有一个问题,我认为是服务器上的格式问题或配置问题,但我是 OData 和 WebAPI 的新手,所以我可能错了。

问题是这样的: 如果我用补丁调用我的 OData 服务,其中像“Mølgaard”这样的非美国字符串包含在指向已声明属性的字段和动态属性中,我会在我的控制器“Mølgaard”上使用我的补丁方法声明的属性,但在动态属性中我得到原始值“M\u00f8lgaard”。预期的行为是在两者中都获得“Mølgaard”,我觉得很奇怪的是动态属性的处理方式似乎与声明的 POCO 属性不同。 我已经使用绑定到我的服务的生成的 MS ODataClient 以及一个名为 Postman 的工具进行了尝试,在这两种情况下,我都使用相同的错误值进入了我的 Patch 方法。

作为 OData 的新手,我尝试添加一个新的序列化程序,如下所述: http://odata.github.io/WebApi/#06-03-costomize-odata-formatter 并从这里的答案中描述的修改: OData WebApi V4 .net - Custom Serialization 我还找到了一个使用 Newtonsoft.Json.JsonConvert 的示例。 简而言之,两者都没有帮助,我猜这两者实际上都不是为了解决这个问题。

我从在这里找到的一个演示项目开始: https://github.com/DevExpress-Examples/XPO_how-to-implement-odata4-service-with-xpo

我已经像这样添加了一个 POCO 类:

    public class OOrder : IDynamicProperties
    {
        [System.ComponentModel.DataAnnotations.Key]
        public int ID { get; set; }
        // SomeText is the declared property and its value 
        // is then repeated in DynamicProperties with another name
        public string SomeText { get; set; }
        public IDictionary<string, object> DynamicProperties { get; set; }
    }

    // I do not know if I need this, I am using
    // it in a map function
    public interface IDynamicProperties
    {
        IDictionary<string, object> DynamicProperties { get; set; }
    }

我的配置非常基本:

    public static class WebApiConfig {
        public static void Register(HttpConfiguration config) {
            config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
            ODataModelBuilder modelBuilder = CreateODataModelBuilder();
            ODataBatchHandler batchHandler = new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer);
            config.MapODataServiceRoute(
                routeName: "ODataRoute",
                routePrefix: null,
                model: modelBuilder.GetEdmModel(),
                batchHandler: batchHandler);
        }

        static ODataModelBuilder CreateODataModelBuilder()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            var openOrder = builder.EntityType<OOrder>();
            openOrder.HasKey(p => p.ID);
            openOrder.Property(p => p.SomeText);
            openOrder.HasDynamicProperties(p => p.DynamicProperties);
            builder.EntitySet<OOrder>("OOrders");

            return builder;
        }
    }

我的控制器上的补丁功能如下所示:

        [HttpPatch]
        public IHttpActionResult Patch([FromODataUri] int key, Delta<OOrder> order)
        {
            if (!ModelState.IsValid) return BadRequest();

            using (UnitOfWork uow = ConnectionHelper.CreateSession()) {
                OOrder existing = getSingle(key, uow);
                if (existing != null) {
                    Order existingOrder = uow.GetObjectByKey<Order>(key);
                    order.CopyChangedValues(existing);
                    mapOpenWithDynamcPropertiesToPersisted(existing, existingOrder);
                    // Intentionally not storing changes for now
                    //uow.CommitChanges();
                    return Updated(existing);
                }
                else {
                    return NotFound();
                }
            }
        }

        private void mapOpenWithDynamcPropertiesToPersisted<TOpen, TPersisted>(TOpen open, TPersisted persisted) 
            where TPersisted : BaseDocument
            where TOpen: IDynamicProperties  {
            if (open != null && persisted != null && open.DynamicProperties != null && open.DynamicProperties.Any()) {
                XPClassInfo ci = persisted.ClassInfo;
                foreach (string propertyName in open.DynamicProperties.Keys) {
                    var member = ci.FindMember(propertyName);
                    if (member != null) {                            
                        object val = open.DynamicProperties[propertyName];
                        // Here, I have tried to deserialize etc
                        member.SetValue(persisted, val);
                    }
                }
            }
        }

在 order.CopyChangedValues(existing) 调用后,现有实例在其“SomeText”属性中包含正确编码的值,但在相应的 Dynamic 属性中不包含。

【问题讨论】:

  • 您的代码在三种情况下将不起作用 1) 如果 int ID 为空。建议将 int 更改为 int?处理 null 2) 如果 ID 不是数字。将使用 TryeParse 3) 如果 IDictionary 有重复的键。确保您测试项目是否已经在字典中。
  • 这似乎是一个奇怪的评论@jdweng,它没有以答案的形式添加任何内容。当它是表的键时,使用不可为空的 int 对我来说是有意义的,Int 是一种类型并且不携带空值或其他任何非 int。关于第 3 点:这里使用 IDictionary,因为它是 OData v4 中动态属性的签名,我使用的是 Dictionary 实现。
  • 如果没有人将值插入数据库,数据库可能有空值。

标签: c# odata


【解决方案1】:

我找到了一些答案,这显然与我没有正确阅读我在问题中提到的文章有关。 答案似乎是一个注入的反序列化器,它使用 json 转换器来转换动态属性,因为它们显然 always 是原始格式。 我的配置现在是这样的:

        public static void Register(HttpConfiguration config) {
            config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
            ODataBatchHandler batchHandler = new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer);
            config.MapODataServiceRoute(
                routeName: "ODataRoute",
                routePrefix: null,
                configureAction: builder => builder.AddService<IEdmModel>(ServiceLifetime.Singleton, sp => CreateODataModel())
                    .AddService<ODataBatchHandler>(ServiceLifetime.Singleton, bb => new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer))
                    .AddService<IEnumerable<IODataRoutingConvention>>(ServiceLifetime.Singleton, sp => ODataRoutingConventions.CreateDefaultWithAttributeRouting("ODataRoute", config))
                    .AddService<Microsoft.AspNet.OData.Formatter.Serialization.ODataSerializerProvider>(ServiceLifetime.Singleton, sp => new MiTestSerializerProvider(sp))
                    .AddService<Microsoft.AspNet.OData.Formatter.Deserialization.ODataDeserializerProvider>(ServiceLifetime.Singleton, sp => new MiDynamicPropertiesDeserializerProvider(sp))
                );
        }

在这种情况下,反序列化器是重要的。 我的反序列化器的开头看起来是这样(它需要提供者/实现耦合):

    public class MiDynamicPropertiesDeserializerProvider : DefaultODataDeserializerProvider
    {
        MiDynamicPropertiesDeserializer _edmSerializer;
        public MiDynamicPropertiesDeserializerProvider(IServiceProvider rootContainer) : base(rootContainer) {
            _edmSerializer = new MiDynamicPropertiesDeserializer(this);
        }

        public override ODataEdmTypeDeserializer GetEdmTypeDeserializer(IEdmTypeReference edmType) {
            switch (edmType.TypeKind()) { // Todo: Do I need more deserializers ?
                case EdmTypeKind.Entity: return _edmSerializer;
                default: return base.GetEdmTypeDeserializer(edmType);
            }
        }
    }

    public class MiDynamicPropertiesDeserializer : ODataResourceDeserializer {
        public MiDynamicPropertiesDeserializer(ODataDeserializerProvider serializerProvider) : base(serializerProvider) { }

        private static Dictionary<Type, Func<object, object>> simpleTypeConverters = new Dictionary<Type, Func<object, object>>() {           
            { typeof(DateTime), d => new DateTimeOffset((DateTime)d)  } // Todo: add converters or is this too simple ?
        };

        public override void ApplyStructuralProperty(object resource, ODataProperty structuralProperty, IEdmStructuredTypeReference structuredType, ODataDeserializerContext readContext) {
            if (structuralProperty != null && structuralProperty.Value is ODataUntypedValue) {
                // Below is a Q&D mapper I am using in my test to represent properties
                var tupl = WebApplication1.Models.RuntimeClassesHelper.GetFieldsAndTypes().Where(t => t.Item1 == structuralProperty.Name).FirstOrDefault();
                if (tupl != null) {
                    ODataUntypedValue untypedValue = structuralProperty.Value as ODataUntypedValue;
                    if (untypedValue != null) {
                        try {
                            object jsonVal = JsonConvert.DeserializeObject(untypedValue.RawValue);
                            Func<object, object> typeConverterFunc;
                            if (jsonVal != null && simpleTypeConverters.TryGetValue(jsonVal.GetType(), out typeConverterFunc))
                            {
                                jsonVal = typeConverterFunc(jsonVal);
                            }
                            structuralProperty.Value = jsonVal;
                        }
                        catch(Exception e) { /* Todo: handle exceptions ? */  }
                    }
                }
            }
            base.ApplyStructuralProperty(resource, structuralProperty, structuredType, readContext);
        }
    }

感谢所有在这方面花费时间的人,我希望其他人会发现此信息有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-25
    • 2019-10-04
    • 1970-01-01
    相关资源
    最近更新 更多