Getting the response in Json

Topics: Web Api
Feb 10, 2012 at 12:09 PM


Is there any way by which we can configure that default output of WCF Get method is in Json format only. The current gives in Xml. I tried with this code

        public List GetRingtones()
            return repo.GetRingtones();

But this doesn't work.

Kindly help.



Feb 10, 2012 at 5:15 PM

I believe you can set the content-type on the response message if you want to be explicit about the response format.

Daniel Roth

Feb 10, 2012 at 7:51 PM

Message handlers can do that

There is no such thing really as a "default".

There is overriding text/html, though.

You set which media types, which formatter uses, when one matches it uses that one. Just so happens that xml is checked first or w.e

I do this:

    public class MediaTypeEnforcementMessageHandler : DelegatingHandler
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            if (request.IsTestingEndpoint())
                return base.SendAsync(request, cancellationToken);
            if (ShouldForceJson(request))
                request.Headers.Accept.Clear(); //clear the accept and replace it to use JSON.
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            return base.SendAsync(request, cancellationToken);
        public static bool ShouldForceJson(HttpRequestMessage request)
            if (request.Content.Headers.ContentType != null &&
                request.Content.Headers.ContentType.MediaType == "text/xml")
                return false;
            if (request.Headers.Accept.Contains(new MediaTypeWithQualityHeaderValue("text/xml")))
                return false;
            return true;