odata格式xml或json无法正常工作

时间:2018-05-16 09:12:17

标签: c# odata

我使用c#和odata,但只输出json格式, 如何添加查询以显示xml格式,我在下面尝试过并且无法正常工作,

我正在使用odata版本4,我尝试添加config.Formatters但无效,

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Net.Http.Formatting;
    using System.Web.Http;
    using System.Web.OData.Builder;
    using System.Web.OData.Extensions;
    using wcod.Models;

namespace wcod
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            ODataModelBuilder builder = new ODataConventionModelBuilder();
            config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);

            builder.EntitySet<LiveMeeting>("LiveMeetings");
             builder.EntitySet<LiveMeetingByType>("LiveMeetingByTypes");

             builder.EntitySet<TimeMarker>("TimeMarkers");        
             var function = builder.Function("TimeMarkerSearch");
             function.Parameter<string>("meetID");
             function.Parameter<string>("keywords");
             function.ReturnsCollectionFromEntitySet<TimeMarker>("TimeMarkers");
            builder.EntitySet<MeetingInfo>("MeetingInfoes");

            config.MapHttpAttributeRoutes();


            //config.Routes.MapODataServiceRoute("odata", "odata/v4", builder.GetEdmModel());
            config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
            config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml");
            config.MapODataServiceRoute("odata", "odata/v4", builder.GetEdmModel());
        }
    }

}

1 个答案:

答案 0 :(得分:0)

对我有用的答案, 在WebApiConfig.cs上

发布以下两行

var odataFormatters = ODataMediaTypeFormatters.Create();
config.Formatters.InsertRange(0, odataFormatters);

并重建项目并运行 尝试将?$format=atom?$format=json放在查询的末尾 如果还有一个过滤器,请改用&$