0

First, to clarify that, my C# API is working properly. I am able to retrieve the json data from my javascript.

But, I am curious, whenever I access my API directly through the browser, it shows this: enter image description here

However, when I access JSON hosted by others (such as myjson), they are able to display the json directly from the browser:

enter image description here

Here's my code briefly,

public Object Get()
{
  ...// form object from my data
  return myObject;
}

Is there any configuration needed?

zeroflaw
  • 554
  • 1
  • 11
  • 23

2 Answers2

2

First of all, you did not specified which framework version you're using. I assume this is WebAPI 2. If not you should clarify.

In WebAPI 2, if your controller returns an object, it will get serialized automatically by a default serialization handler. This default handler will return xml by default, but also return json if you ask for it. You can ask for the JSON version by specifying in your HTTP request accepts header. You can also change the code such that it will no longer return xml by default.

The following code is copied directly from: How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

I just add the following in App_Start / WebApiConfig.cs class in my MVC Web API project.

config.Formatters.JsonFormatter.SupportedMediaTypes
    .Add(new MediaTypeHeaderValue("text/html") );
Community
  • 1
  • 1
1283822
  • 1,832
  • 17
  • 13
1

On your Application_Start you can configure the formatter as needed ex:

protected void Application_Start()
{
     GlobalConfiguration.Configure(ServerConfig.Configure);
}

void Configure(HttpConfiguration config)
{
      var formatters = config.Formatters;
      var jsonFormatter = formatters.JsonFormatter;
      // "text/html" is the default browser request content type
      jsonFormatter.SupportedMediaTypes.Add(new 
      MediaTypeHeaderValue("text/html"));
      WebApiConfig.Register(config);
      RegisterDependencies();
 }
Chandan Kumar
  • 4,570
  • 4
  • 42
  • 62
Ashraf
  • 66
  • 5