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 886215
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T13:01:57+00:00 2026-05-15T13:01:57+00:00

UPDATE 10/19/2010 I know I asked this question a while ago, but the workarounds

  • 0

UPDATE 10/19/2010
I know I asked this question a while ago, but the workarounds shown in these answers are hardly satisfactory, and this is still a common problem for many. WCF just isn’t flexible. I started my own open source C# library for creating REST services without WCF. Check restcake.net or rest.codeplex.com for info on said library.
END UPDATE

UPDATE 8/2/2012
ASP.NET Web API (previously WCF Web API, the replacement for REST WCF) uses Json.NET by default
END UPDATE

The DataContractJsonSerializer is unable to handle many scenarios that Json.Net handles just fine when properly configured (specifically, cycles).

A service method can either return a specific object type (in this case a DTO), in which case the DataContractJsonSerializer will be used, or I can have the method return a string, and do the serialization myself with Json.Net. The problem is that when I return a json string as opposed to an object, the json that is sent to the client is wrapped in quotes.

Using DataContractJsonSerializer, returning a specific object type, the response is:
{"Message":"Hello World"}

Using Json.Net to return a json string, the response is:
"{\"Message\":\"Hello World\"}"

I do not want to have to eval() or JSON.parse() the result on the client, which is what I would have to do if the json comes back as a string, wrapped in quotes. I realize that the behavior is correct; it’s just not what I want/need. I need the raw json; the behavior when the service method’s return type is an object, not a string.

So, how can I have my method return an object type, but not use the DataContractJsonSerializer? How can I tell it to use the Json.Net serializer instead?

Or, is there someway to directly write to the response stream? So I can just return the raw json myself? Without the wrapping quotes?

Here is my contrived example, for reference:

[DataContract]
public class SimpleMessage
{
    [DataMember]
    public string Message { get; set; }
}

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class PersonService
{
    // uses DataContractJsonSerializer
    // returns {"Message":"Hello World"}
    [WebGet(UriTemplate = "helloObject")]
    public SimpleMessage SayHelloObject()
    {
        return new SimpleMessage("Hello World");
    }

    // uses Json.Net serialization, to return a json string
    // returns "{\"Message\":\"Hello World\"}"
    [WebGet(UriTemplate = "helloString")]
    public string SayHelloString()
    {
        SimpleMessage message = new SimpleMessage() { Message = "Hello World" };
        string json = JsonConvert.Serialize(message);
        return json;
    }

    // I need a mix of the two.  Return an object type, but use the Json.Net serializer.
}
  • 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-15T13:01:57+00:00Added an answer on May 15, 2026 at 1:01 pm

    I finally figured out a solution to this. It’s not what I would have preferred (which would be to return the specific object type, and somehow instruct WCF to use a Json.Net serializer, instead of the DataContractJsonSerializer), but it is working great, and it’s simple and clear.

    Extending my contrived example using this new solution:

    [WebGet(UriTemplate = "hello")]
    public void SayHello()
    {
        SimpleMessage message = new SimpleMessage() {Message = "Hello World"};
        string json = JsonConvert.Serialize(message);
        HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
        HttpContext.Current.Response.Write(json);
    }
    

    Note the return type of void. We do not return anything, since it would be serialized with DataContractJsonSerializer. Instead, I write directly to the response output stream. Since the return type is void, the processing pipeline doesn’t set the content-type to the default type of “application/json”, so I set it explicitly.

    Because this uses HttpContext, I’m guessing it will only work if you have [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] on your service class, since that will force requests to the service to go through the ASP.NET pipeline. Without the asp.net compatibility, the HttpContext will not be available, since wcf hosting is supposed to be host agnostic.

    Using this method, the results look perfect in firebug for GET requests. Correct content-type, correct content length, and raw json, not wrapped in quotes. And, I’m getting the serialization I want using Json.Net. Best of both worlds.

    I’m not 100% positive of what obstacles I might run into regarding deserialization, when my service methods have [DataContract] object types as input parameters. I’m assuming the DataContractJsonSerializer will be used for that too. Will cross that bridge when I come to it…if it creates a problem. It hasn’t so far, with my simple DTOs.

    UPDATE
    See Oleg’s answer (the UPDATE2 part). He changes the return type of the service method from void to System.ServiceModel.Channels.Message, and rather than using HttpContext.Current.Response.Write(), he uses:

    return WebOperationContext.Current.CreateTextResponse (json,
        "application/json; charset=utf-8", Encoding.UTF8);
    

    Which is indeed a better solution. Thank you Oleg.

    UPDATE 2
    There is yet another way of accomplishing this. Change your service’s return type from Message to Stream, and return this:

    WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
    return new MemoryStream(System.Text.Encoding.UTF8.GetBytes(json));
    

    I haven’t done any specific tests, but it’s possible that this would be a better choice for methods that could potentially return large amounts of data. I don’t know if that matters for non-binary data though. Anyway, a thought.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i know this question was asked before but i have this very weird beginner
Update: Check out this follow-up question: Gem Update on Windows - is it broken?
Update: Please read this question in the context of design principles, elegance, expression of
This question ( .net Compact Framework 4.0 ) asked this back before the release
UPDATE: Focus your answers on hardware solutions please. What hardware/tools/add-in are you using to
Update: Now that it's 2016 I'd use PowerShell for this unless there's a really
Update: Thanks for the suggestions guys. After further research, I’ve reformulated the question here:
Update 2011-Jan-06: Believe it or not, I went ahead and incorporated this interface into
I want to update service references in a Visual Studio 2010 solution by using
Update: Solved, with code I got it working, see my answer below for the

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.