How do I get ASP.NET Web API to return JSON instead of XML using Chrome?
By default, ASP.NET Web API uses content negotiation to decide whether to return JSON or XML. If you’re seeing XML instead of JSON in Chrome, here are some straightforward ways to ensure JSON responses:
1. Remove or Disable the XML Formatter
One quick fix is to remove the XML formatter entirely in your WebApiConfig.cs
:
public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Other configurations... // Remove the XML formatter config.Formatters.Remove(config.Formatters.XmlFormatter); // Ensure JSON is the default, especially for text/html config.Formatters.JsonFormatter.SupportedMediaTypes .Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html")); } }
Now your Web API will return JSON for all requests unless explicitly asked for something else.
2. Set the Accept
Header to application/json
Most browsers automatically request HTML or XML when you type a URL in the address bar. To override this, explicitly request JSON:
-
Option A: Use a REST client or a tool like Postman or cURL that lets you set HTTP headers.
curl -H "Accept: application/json" https://localhost:5001/api/users
-
Option B: Install a Chrome extension like “ModHeader” or “Advanced REST client” to manually add the
Accept: application/json
header in your browser requests.
3. Confirm Your Response is Valid JSON
Once configured, calling your API in Chrome should return JSON. If you’re still seeing XML, double-check:
- Other Formatters: Make sure no custom or third-party formatters are returning XML.
- Routes: If you have multiple endpoints or custom routes, confirm they all share the same configuration.
- Caching Issues: Clear your browser cache or use an Incognito window to ensure you see the updated behavior.
Level Up Your Coding Skills
If you’re looking to grow as a developer—both in .NET and broader system design—here are two resources from DesignGurus.io worth exploring:
-
Grokking the Coding Interview: Patterns for Coding Questions
Learn to recognize 20+ key coding patterns to solve interview challenges efficiently. -
Grokking the System Design Interview
Dive into distributed systems, architecture trade-offs, and real-world scalability solutions.
Final Thoughts
Getting ASP.NET Web API to return JSON in Chrome typically involves setting JSON as the default response type (by removing the XML formatter) or manually specifying the Accept
header in your requests. Once configured properly, you’ll enjoy cleaner integration between your front-end and back-end, with data responses in the widely used JSON format.