Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

Is it possible to return json by default from the ASP.NET Web API instead of XML?

share|improve this question
    
This sort of breaks the pattern of keeping the web api agnostic. If you send an Accept : application/json in the headers of your ajax request, WebAPI will respond in Json. Can I see your ajax request? – gideon Dec 1 '12 at 17:11
    
Thanks mate. Thats all I needed. I just seen a video tutorial from pluralsight using the web api and the bloke put in the api url route and it responded with json straight in the browser. So there was no ajax request. It was only website.com/api/control – Wesley Skeen Dec 1 '12 at 17:17
    
You shouldn't even need the Accept header. If you don't have an Accept header on a GET request, you should get JSON back from WebAPI. – Youssef Moussaoui Dec 2 '12 at 3:21

2 Answers 2

up vote 15 down vote accepted

It's what is done by default. JsonMediaTypeFormatter is registered as the first MediaTypeFormatter and if the client doesn't request the response in a specific format, ASP.NET Web API pipeline gives you the response in application/json format.

If what you want is to only support application/json, remove all other formatters and only leave JsonMediaTypeFormatter:

public static void Configure(HttpConfiguration config) {

    var jqueryFormatter = config.Formatters.FirstOrDefault(x => x.GetType() == typeof(JQueryMvcFormUrlEncodedFormatter));
    config.Formatters.Remove(config.Formatters.XmlFormatter);
    config.Formatters.Remove(config.Formatters.FormUrlEncodedFormatter);
    config.Formatters.Remove(jqueryFormatter);
}
share|improve this answer
    
That works for me. thanks – Bilal lilla Dec 11 '13 at 13:11

@tugberk's solution doesn't really accomplish the goal of changing the default formatter. It simply makes JSON the only option. If you want to make JSON the default and still support all of the other types, you can do the following:

public static void Configure(HttpConfiguration config) {
    // move the JSON formatter to the front of the line
    var jsonFormatter = config.Formatters.JsonFormatter;
    config.Formatters.Remove(jsonFormatter);
    config.Formatters.Insert(0, jsonFormatter);
}

Note: JSON is the default formatter as of Web API 2.0.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.