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:
Here's my code briefly,
public Object Get()
{
...// form object from my data
return myObject;
}
Is there any configuration needed?
2 Answers 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") );
-
My bad for not specifying this. But ya, modifying the webapiconfing.cs is the solution.zeroflaw– zeroflaw2017年03月29日 06:05:52 +00:00Commented Mar 29, 2017 at 6:05
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();
}