【问题标题】:Extending OData deserializer扩展 OData 反序列化器
【发布时间】:2015-03-05 12:33:51
【问题描述】:

我正在使用 ASP.NET Web API 实现 OData v3 API 端点。

我注意到我的 Web API 中的 CreateLink 方法仅在客户端为现有条目执行 SetLink 时才被调用。

另一方面,如果我使用链接 (SetLink) 创建新条目,则不会调用我的 Web API 上的 CreateLink。相反,链接包含在创建实体的 POST 请求中:

<?xml version=\"1.0\" encoding=\"utf-8\"?>
    <entry xmlns=\"http://www.w3.org/2005/Atom\" xmlns:d=\"http://schemas.microsoft.com/ado/2007/08/dataservices\" xmlns:m=\"http://schemas.microsoft.com/ado/2007/08/dataservices/metadata\">
        <category term=\"TestProject.Entities.TestEntity\" scheme=\"http://schemas.microsoft.com/ado/2007/08/dataservices/scheme\" />
        <link rel=\"http://schemas.microsoft.com/ado/2007/08/dataservices/related/TestEntityChild\" type=\"application/atom+xml;type=entry\" title=\"TestEntityChild\" href=\"http://localhost:18995/odata/TestEntityChildren(2)\" />
        <id />
        <title />
        <updated>2015-03-05T08:28:05Z</updated>
        <author>
            <name />
        </author>
        <content type=\"application/xml\">
            <m:properties>
                <d:Id m:type=\"Edm.Int32\">0</d:Id>
                <d:OtherProperty m:type=\"Edm.Int32\" m:null=\"true\" />
            </m:properties>
        </content>
    </entry>

如何将此链接绑定到传递给我的 ODataController 操作的模型?

我的第一个想法是扩展 OData 反序列化器。由于 ODataEntityDeserializer 是内部类,我无法这样做。也许有一些更简单的方法?

【问题讨论】:

    标签: c# asp.net asp.net-web-api odata


    【解决方案1】:

    您可以通过在 WebAPIConfig.cs 中添加格式化程序来扩展 odata 反序列化。

        public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
            HttpServer APIServer = new HttpServer(config);
    
            config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
            config.Formatters.JsonFormatter.MaxDepth = 2048;
            config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    
            config.Services.Replace(typeof(IExceptionHandler), new CustomExceptionHandler());
            var odataFormatters = ODataMediaTypeFormatters.Create(new ODataSerialzer(), new ODataDeserialzer());
            config.Formatters.Clear();
            config.Formatters.AddRange(odataFormatters);
    
            config.MapODataServiceRoute(routeName: "OData",
                routePrefix: "",
                model: APIConfiguration.GetModel(),
                batchHandler: new DefaultODataBatchHandler(APIServer));
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-09
      • 1970-01-01
      相关资源
      最近更新 更多