Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6987643
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T18:57:50+00:00 2026-05-27T18:57:50+00:00

How can I modify incoming JSON to a WCF REST service before it is

  • 0

How can I modify incoming JSON to a WCF REST service before it is converted to a Message?

For example, if I submit the following:

{
    "Name": "Joe Bloggs",
    "Age": 30
}

I’d like all whitespace to be stripped so the packet body is converted to:

{"Name":"Joe Bloggs","Age":30}

I’m trying to work around a problem in System.Runtime.Serialization.Json.XmlJsonReader that I’ve found where JSON is not converted to XML properly if there is any whitespace in the packet. Since I can’t guarantee that all of my clients will send whitespace-free JSON I’d like some kind of pre-processor that will strip whitespace from the JSON before it is passed to XmlJsonReader.

I’ve looked into implementing a custom IDispatchMessageInspector using the AfterReceiveRequest method. but this is too late as the JSON has already been converted to a Message containing incorrect XML. I’d need to modify the JSON before this stage but I can’t find any extensibility points that far back in the process.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T18:57:51+00:00Added an answer on May 27, 2026 at 6:57 pm

    If you want to deal with the message before it’s decoded, you’ll need a custom message encoder for that (that’s the component which converts between the bytes in the wire and the message object). You can find more information about custom encoders at http://blogs.msdn.com/b/carlosfigueira/archive/2011/11/09/wcf-extensibility-message-encoders.aspx.

    The custom encoder below strips the white spaces from the JSON document. The default writer created by JsonReaderWriterFactory.CreateJsonWriter doesn’t do any pretty printing, so that’s essentially what you need.

    public class StackOverflow_8670954
    {
        [DataContract(Name = "Person", Namespace = "MyNamespace")]
        public class Person
        {
            [DataMember]
            public string Name { get; set; }
            [DataMember]
            public int Age { get; set; }
    
            public override string ToString()
            {
                return string.Format("Person[Name={0},Age={1}]", Name, Age);
            }
        }
        [DataContract(Name = "Employee", Namespace = "MyNamespace")]
        public class Employee : Person
        {
            [DataMember]
            public int EmployeeId { get; set; }
    
            public override string ToString()
            {
                return string.Format("Employee[Id={0},Name={1}]", EmployeeId, Name);
            }
        }
        [ServiceContract]
        public interface ITest
        {
            [WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
            [ServiceKnownType(typeof(Employee))]
            string PrintPerson(Person person);
        }
        public class Service : ITest
        {
            public string PrintPerson(Person person)
            {
                return person.ToString();
            }
        }
        static Binding GetBinding()
        {
            var result = new CustomBinding(new WebHttpBinding());
            for (int i = 0; i < result.Elements.Count; i++)
            {
                MessageEncodingBindingElement mebe = result.Elements[i] as MessageEncodingBindingElement;
                if (mebe != null)
                {
                    result.Elements[i] = new MyEncodingBindingElement(mebe);
                    break;
                }
            }
            return result;
        }
        class MyEncodingBindingElement : MessageEncodingBindingElement
        {
            MessageEncodingBindingElement inner;
            public MyEncodingBindingElement(MessageEncodingBindingElement inner)
            {
                this.inner = inner;
            }
    
            public override MessageEncoderFactory CreateMessageEncoderFactory()
            {
                return new MyEncoderFactory(this.inner.CreateMessageEncoderFactory());
            }
    
            public override MessageVersion MessageVersion
            {
                get { return this.inner.MessageVersion; }
                set { this.inner.MessageVersion = value; }
            }
    
            public override BindingElement Clone()
            {
                return new MyEncodingBindingElement(this.inner);
            }
    
            public override bool CanBuildChannelListener<TChannel>(BindingContext context)
            {
                return context.CanBuildInnerChannelListener<TChannel>();
            }
    
            public override IChannelListener<TChannel> BuildChannelListener<TChannel>(BindingContext context)
            {
                context.BindingParameters.Add(this);
                return context.BuildInnerChannelListener<TChannel>();
            }
    
            class MyEncoderFactory : MessageEncoderFactory
            {
                private MessageEncoderFactory inner;
    
                public MyEncoderFactory(MessageEncoderFactory inner)
                {
                    this.inner = inner;
                }
    
                public override MessageEncoder Encoder
                {
                    get { return new MyEncoder(this.inner.Encoder); }
                }
    
                public override MessageVersion MessageVersion
                {
                    get { return this.inner.MessageVersion; }
                }
            }
    
            class MyEncoder : MessageEncoder
            {
                private MessageEncoder inner;
    
                public MyEncoder(MessageEncoder inner)
                {
                    this.inner = inner;
                }
    
                public override string ContentType
                {
                    get { throw new NotImplementedException(); }
                }
    
                public override string MediaType
                {
                    get { throw new NotImplementedException(); }
                }
    
                public override MessageVersion MessageVersion
                {
                    get { throw new NotImplementedException(); }
                }
    
                public override bool IsContentTypeSupported(string contentType)
                {
                    return this.inner.IsContentTypeSupported(contentType);
                }
    
                public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)
                {
                    if (IsJsonContentType(contentType))
                    {
                        // the encoder can also support other types of content (raw, xml), so we don't want to deal with those
    
                        MemoryStream writeStream = new MemoryStream();
                        XmlDictionaryWriter jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(writeStream, Encoding.UTF8, false);
                        XmlDictionaryReader jsonReader = JsonReaderWriterFactory.CreateJsonReader(buffer.Array, buffer.Offset, buffer.Count, XmlDictionaryReaderQuotas.Max);
                        jsonWriter.WriteNode(jsonReader, true);
                        jsonWriter.Flush();
    
                        byte[] newBuffer = bufferManager.TakeBuffer(buffer.Offset + (int)writeStream.Position);
                        Array.Copy(writeStream.GetBuffer(), 0, newBuffer, buffer.Offset, (int)writeStream.Position);
                        bufferManager.ReturnBuffer(buffer.Array);
                        buffer = new ArraySegment<byte>(newBuffer, buffer.Offset, (int)writeStream.Position);
                        writeStream.Dispose();
                        jsonReader.Close();
                        jsonWriter.Close();
                    }
    
                    return this.inner.ReadMessage(buffer, bufferManager, contentType);
                }
    
                static bool IsJsonContentType(string contentType)
                {
                    return contentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase) ||
                        contentType.StartsWith("text/json", StringComparison.OrdinalIgnoreCase);
                }
    
                public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType)
                {
                    throw new NotSupportedException("Streamed transfer not supported");
                }
    
                public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
                {
                    return this.inner.WriteMessage(message, maxMessageSize, bufferManager, messageOffset);
                }
    
                public override void WriteMessage(Message message, Stream stream)
                {
                    throw new NotSupportedException("Streamed transfer not supported");
                }
            }
        }
        public static void Test()
        {
            string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
            ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
            host.AddServiceEndpoint(typeof(ITest), GetBinding(), "").Behaviors.Add(new WebHttpBehavior());
            host.Open();
            Console.WriteLine("Host opened");
    
            string[] inputs = new string[]
            {
                "{\"__type\":\"Employee:MyNamespace\",\"Age\":33,\"Name\":\"John\",\"EmployeeId\":123}",
                "{  \"__type\":\"Employee:MyNamespace\",\"Age\":33,\"Name\":\"John\",\"EmployeeId\":123}",
            };
    
            foreach (string input in inputs)
            {
                WebClient c = new WebClient();
                c.Headers[HttpRequestHeader.ContentType] = "application/json";
                Console.WriteLine(c.UploadString(baseAddress + "/PrintPerson", input));
            }
    
            Console.Write("Press ENTER to close the host");
            Console.ReadLine();
            host.Close();
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is there anyway I can modify this code example #include <stdlib.h> #include <iostream> class
How I can modify that example http://www.extjs.com/deploy/dev/examples/tree/reorder.html for RESTful support? When we click on
I'm creating a small page where users can modify the name of categories and
Could someone tell me how I can modify the html before I insert it
Can anybody confirm or deny that I can modify default styles provided by StyleCop
I have a form where users can modify a collection of objects using a
I am trying to create an application can modify properties in IL to create
I'm trying to understand code that I bought so I can modify it. In
Because wikipedia is open source, I can modify anything I want. But what happens
How can I modify a SharePoint site so that versioning is turned on by

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.