如何使用AspNet.OData v6注册OData Serializer Provider

时间:2017-11-13 05:50:31

标签: asp.net odata

Microsoft.AspNet.Odata改变了注册序列化程序等服务的方式。新格式应该是什么样的?

1 个答案:

答案 0 :(得分:0)

您的新配置应该如下所示。您需要添加至少前两个服务(IEdmModel和IEnumerable IODataRoutingConvention),然后您可以添加自己的。例如,自定义odata序列化程序提供程序。

using Boomerang.OData;
using Boomerang.Models;
using Microsoft.OData;
using Microsoft.OData.Edm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
using System.Web.OData.Formatter;
using System.Web.OData.Formatter.Serialization;
using System.Web.OData.Routing.Conventions;

namespace Boomerang
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.MapODataServiceRoute(
                "ODataRoute",
                "api",
                containerBuilder => containerBuilder
                .AddService<IEdmModel>(ServiceLifetime.Singleton, s => BuildEdmModelForOData())
                .AddService<IEnumerable<IODataRoutingConvention>>(ServiceLifetime.Singleton, sp =>
                    ODataRoutingConventions.CreateDefaultWithAttributeRouting("ODataRoute", config))
                .AddService<ODataSerializerProvider>(ServiceLifetime.Singleton, s => new CustomODataSerializerProvider(s))
                );

            config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
        }

        public static IEdmModel BuildEdmModelForOData()
        {
            ODataConventionModelBuilder
                oDataConventionModelBuilder = new ODataConventionModelBuilder();

            // Build model here
            oDataConventionModelBuilder.EntitySet<Post>("Posts");
            oDataConventionModelBuilder.EntitySet<Feeling>("Feelings");

            return oDataConventionModelBuilder.GetEdmModel();
        }
    }
}

我正在添加此答案,因为大多数在线指南都会为6之前的版本提供说明。此信息可在此处找到:http://odata.github.io/WebApi/#13-04-DependencyInjection