无法使WCF json.net默认序列化器工作

时间:2016-06-02 19:19:03

标签: c# wcf json.net mediatypeformatter

我知道这些年来有几篇帖子: Sorry they wont let me add this many links ??

链接一些..但这些都不完整,并引用了所需的全部技术......通常引用一个难以找到的类......我将发布我的内容和底线当格式化程序DO进入formatters集合时,不会调用自定义格式化程序。现在可能是我使用完全错误的解决方案,但似乎没有解决方案......这应该很容易实现。我已经尝试了所有可能的内容类型以及以下内容:

型号:

        public class TEST_Hotel : IHotelOption
{

    public int AlternateCount{get;set;}                            
    public float AverageBaseRate{get;set;}       
    public List<string> policyViolations{get;set;}                 
    public int TravelerBookings{get;set;}                       
     [JsonProperty("hotelId")]
    public string VendorHotelID{get;set;}     

}

添加[DataContract] [DataMember]属性当然会起作用,因为它将使用DataContract序列化程序而不是自定义序列化程序。注意:由于未使用自定义json.net格式化程序,因此无法识别JsonProperty。

服务:

 [OperationContract]
    [Description("Retrieves a list of hotel objects based on search parameters")]
    [WebGet(
         BodyStyle = WebMessageBodyStyle.WrappedRequest,
  //      ResponseFormat = WebMessageFormat.Json,
   //     RequestFormat = WebMessageFormat.Json,
        UriTemplate = "GetHotels?queryparams={parameters}")]
    public HotelResults GetHotels(string parameters)
    {
        return worker.GetHotels(parameters);
    }

全局:

          using System;
         using System.ServiceModel.Activation;
         using System.Web.Routing;
         using System.Web;
         using System.Linq;
        using System.Web.Http;

    namespace HotelService
    {
    public class Global : System.Web.HttpApplication
    {
    private void Application_Start(object sender, EventArgs e)
    {

        RegisterRoutes();
    }


    private void RegisterRoutes()
    {
        RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(Hotels)));
        GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonNetMediaTypeFormatter() );
    }


}

    }

JsonNetMediaTypeFormatter:

     using Newtonsoft.Json;
     using System;
     using System.Collections.Generic;
     using System.Collections.ObjectModel;
     using System.IO;
     using System.Linq;
     using System.Net;
     using System.Net.Http;
     using System.Net.Http.Formatting;
     using System.Net.Http.Headers;
     using System.Threading.Tasks;
     using System.Web;

     namespace HotelService
     {

    public sealed class JsonNetMediaTypeFormatter : JsonMediaTypeFormatter
    {
        public JsonSerializer Serializer
        {
            get;
            private set;
        }

        public JsonNetMediaTypeFormatter(JsonSerializer serializer = null)
        {

            Collection<MediaTypeHeaderValue> supportedMediaTypes = base.SupportedMediaTypes;
            MediaTypeHeaderValue mediaTypeHeaderValue = new MediaTypeHeaderValue("application/json");
            mediaTypeHeaderValue.CharSet = "UTF-8";
            supportedMediaTypes.Add(mediaTypeHeaderValue);
            Collection<MediaTypeHeaderValue> mediaTypeHeaderValues = base.SupportedMediaTypes;
            MediaTypeHeaderValue mediaTypeHeaderValue1 = new MediaTypeHeaderValue("text/json");
            mediaTypeHeaderValue1.CharSet = "UTF-8";
            mediaTypeHeaderValues.Add(mediaTypeHeaderValue1);
            this.Serializer = (serializer != null ? serializer : new JsonSerializer());


        }

        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            return readStream.ReadAsJson(type, this.Serializer);
        }

        public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
        {
            return writeStream.WriteAsJson(value, this.Serializer);
        }

        public override bool CanReadType(Type type)
        {
            return false;
        }

        public override bool CanWriteType(Type type)
        {
            return true;
        }



    }

    internal static class StreamExtensions
    {
        internal static Task<object> ReadAsJson(this Stream stream, Type instanceType, JsonSerializer serializer)
        {
            if (stream == null)
            {
                return null;
            }
            return Task<object>.Factory.StartNew(() =>
            {
                object obj1;
                using (JsonTextReader reader = new JsonTextReader(new StreamReader(stream)))
                {
                    object obj = serializer.Deserialize(reader);
                    obj1 = (obj.GetType().IsSubclassOf(instanceType) ? obj : serializer.Deserialize(reader, instanceType));
                }
                return obj1;
            });
        }

        internal static Task WriteAsJson(this Stream stream, object instance, JsonSerializer serializer)
        {
            if (instance == null)
            {
                return null;
            }
            return Task.Factory.StartNew(() =>
            {
                using (JsonTextWriter writer = new JsonTextWriter(new StreamWriter(stream)))
                {
                    serializer.Serialize(writer, instance);
                    writer.Flush();
                }
            });
        }
        }

       }

软件包:

    <packages>
      <package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net451" />
       <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net451" />
       <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net451" />
       <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net451" />
        <package id="Newtonsoft.Json" version="8.0.3" targetFramework="net451" />
      </packages>

如果我删除了Service ResponseFormat,那么如果我把它放回去就会返回xml返回json但是没有使用自定义格式化程序。打破全局我可以在集合的0索引处看到自定义格式化程序。它会显示一个映射器或某些绑定丢失。

0 个答案:

没有答案