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

  • SEARCH
  • Home
  • 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 8185687
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T01:56:09+00:00 2026-06-07T01:56:09+00:00

I’m writing a simple client for a web service using WCF. Unfortunately, the web

  • 0

I’m writing a simple client for a web service using WCF. Unfortunately, the web service only answers with JSONP messages, not plain JSON.

Is that possible to use built-in features from .NET 4.0 to do this or do I need to extend something else to strip function name, { and } from the answer I get from the server? I know how to read JSON responses, but not JSONP yet.

  • 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-06-07T01:56:11+00:00Added an answer on June 7, 2026 at 1:56 am

    What you need is a custom message encoder. On the server side, it’s the encoder which adds the padding (function call) to the response, so you need something similar on the client side to remove that padding before handling the message (likely delegating it to another encoder). The other thing you’ll need to worry about at the encoder is that often the content-type used for JSONP (application/x-javascript) is not recognized as a JSON content-type (because it’s not, it’s a function call), so the encoder should also “translate” that content-type into one which is understood by the encoder to which the call is delegated.

    The code below shows an example of such an encoder. The service has been modified to always wrap the result, as you mentioned your service does.

    public class StackOverflow_11255528
    {
        [ServiceContract]
        public interface ICalculator
        {
            [WebGet(ResponseFormat = WebMessageFormat.Json)]
            int Add(int x, int y);
            [WebGet(ResponseFormat = WebMessageFormat.Json)]
            int Subtract(int x, int y);
        }
        [ServiceContract]
        public class CalculatorService
        {
            [WebGet(ResponseFormat = WebMessageFormat.Json)]
            public Stream Add(int x, int y)
            {
                return ReturnWrapped(x + y);
            }
    
            [WebGet(ResponseFormat = WebMessageFormat.Json)]
            public Stream Subtract(int x, int y)
            {
                return ReturnWrapped(x - y);
            }
    
            private Stream ReturnWrapped(int result)
            {
                string callback = "Something";
                string response = string.Format("{0}({1});", callback, result);
                WebOperationContext.Current.OutgoingResponse.ContentType = "application/x-javascript";
                return new MemoryStream(Encoding.UTF8.GetBytes(response));
            }
        }
        public class JsonpAwareClientMessageEncodingBindingElement : MessageEncodingBindingElement
        {
            WebMessageEncodingBindingElement webEncoding;
    
            public JsonpAwareClientMessageEncodingBindingElement()
            {
                this.webEncoding = new WebMessageEncodingBindingElement();
            }
    
            public override MessageEncoderFactory CreateMessageEncoderFactory()
            {
                return new JsonpAwareClientMessageEncoderFactory(this.webEncoding.CreateMessageEncoderFactory());
            }
    
            public override MessageVersion MessageVersion
            {
                get { return this.webEncoding.MessageVersion; }
                set { this.webEncoding.MessageVersion = value; }
            }
    
            public override BindingElement Clone()
            {
                return new JsonpAwareClientMessageEncodingBindingElement();
            }
    
            public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context)
            {
                context.BindingParameters.Add(this);
                return context.BuildInnerChannelFactory<TChannel>();
            }
    
            class JsonpAwareClientMessageEncoderFactory : MessageEncoderFactory
            {
                private MessageEncoderFactory factory;
    
                public JsonpAwareClientMessageEncoderFactory(MessageEncoderFactory factory)
                {
                    this.factory = factory;
                }
    
                public override MessageEncoder Encoder
                {
                    get { return new JsonpAwareClientMessageEncoder(this.factory.Encoder); }
                }
    
                public override MessageVersion MessageVersion
                {
                    get { return this.factory.MessageVersion; }
                }
            }
    
            class JsonpAwareClientMessageEncoder : MessageEncoder
            {
                private MessageEncoder encoder;
    
                public JsonpAwareClientMessageEncoder(MessageEncoder encoder)
                {
                    this.encoder = encoder;
                }
    
                public override string ContentType
                {
                    get { return this.encoder.ContentType; }
                }
    
                public override string MediaType
                {
                    get { return this.encoder.MediaType; }
                }
    
                public override MessageVersion MessageVersion
                {
                    get { return this.encoder.MessageVersion; }
                }
    
                public override bool IsContentTypeSupported(string contentType)
                {
                    if (contentType == "application/x-javascript")
                    {
                        contentType = "application/json";
                    }
    
                    return this.encoder.IsContentTypeSupported(contentType);
                }
    
                public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)
                {
                    if (contentType == "application/x-javascript")
                    {
                        contentType = "application/json";
                    }
    
                    byte openParenthesis = (byte)'(';
                    byte closeParenthesis = (byte)')';
                    int startOfParenthesis = buffer.Offset;
                    int count = buffer.Count;
                    while (buffer.Array[startOfParenthesis] != openParenthesis)
                    {
                        startOfParenthesis++;
                        count--;
                    }
    
                    // Skipped 'Func', now skipping '('
                    startOfParenthesis++;
                    count--;
    
                    // Now need to trim the closing parenthesis and semicolon, if any
                    int endOfParenthesis = buffer.Offset + buffer.Count - 1;
                    while (buffer.Array[endOfParenthesis] != closeParenthesis)
                    {
                        endOfParenthesis--;
                        count--;
                    }
    
                    // Skipped back to ')', now remove it
                    endOfParenthesis--;
                    count--;
    
                    return this.encoder.ReadMessage(new ArraySegment<byte>(buffer.Array, startOfParenthesis, count), bufferManager, contentType);
                }
    
                public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType)
                {
                    throw new NotSupportedException("Streamed mode not supported");
                }
    
                public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
                {
                    return this.encoder.WriteMessage(message, maxMessageSize, bufferManager, messageOffset);
                }
    
                public override void WriteMessage(Message message, Stream stream)
                {
                    throw new NotSupportedException("Streamed mode not supported");
                }
            }
        }
        public static void Test()
        {
            string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
            ServiceHost host = new ServiceHost(typeof(CalculatorService), new Uri(baseAddress));
            WebHttpBinding binding = new WebHttpBinding { CrossDomainScriptAccessEnabled = true };
            host.AddServiceEndpoint(typeof(CalculatorService), binding, "").Behaviors.Add(new WebHttpBehavior());
            host.Open();
            Console.WriteLine("Host opened");
    
            WebClient c = new WebClient();
            Console.WriteLine(c.DownloadString(baseAddress + "/Add?x=5&y=8&callback=Func"));
    
            CustomBinding clientBinding = new CustomBinding(
                new JsonpAwareClientMessageEncodingBindingElement(),
                new HttpTransportBindingElement { ManualAddressing = true });
            ChannelFactory<ICalculator> factory = new ChannelFactory<ICalculator>(clientBinding, new EndpointAddress(baseAddress));
            factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
            ICalculator proxy = factory.CreateChannel();
            Console.WriteLine(proxy.Subtract(456, 432));
    
            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

That's pretty much it. I'm using Nokogiri to scrape a web page what has
Seemingly simple, but I cannot find anything relevant on the web. What is the
I'm making a simple page using Google Maps API 3. My first. One marker
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I want use html5's new tag to play a wav file (currently only supported
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I am doing a simple coin flipping experiment for class that involves flipping a

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.