MVC 4 - Web Api and JSON? - asp.net-mvc-4

I'm ramping up on MVC 4's Web API and I'm a bit confused about the default formatting. I want the API data to be in JSON. However, it's returning it in XML. According to the MVC 4 getting started video at http://www.asp.net/web-api/videos/getting-started/your-first-web-api, it should be JSON by default. But when I create a new Web Api project and run the sample, I get this:
<ArrayOfstring><string>value1</string><string>value2</string></ArrayOfstring>
I've been running around in circles trying to get this in JSON but apparently there is a lot of misinformation about this. Such as:
If I add "application/json" to the content type header, it should return JSON. This doesn't work, but I'm suspecting I don't have the header variable name right as I'm not finding the exact name to use. I've tried "Content-Type" and "contentType" in the request headers with no luck. Besides, I want JSON by default, not according to header info.
If I create a JsonFormatter and add it in Application_Start GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonNetFormatter(serializerSettings)); It should do the trick. But I gathered this depreciated as none of the examples are working.
What could I do, something simple preferably, to output data in JSON format by default?

Add this to GLOBAL.ASAX to get the response to be application/json
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
So it should look like this in context:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
BundleTable.Bundles.RegisterTemplateBundles();
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
}
OR if you need to preserve XML as a media type you could instead edit App_Start/WebApiConfig.cs:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html") );
Which makes JSON the default response for a web browser but returns text/html.
Source

I want the API data to be in JSON. However, it's returning it in XML
How are you accessing your webapi? Are you using Chrome to access your webapi service (as Nick has mentioned in the comment)? Chrome adds the Accept header application/xml to the request...
If I add "application/json" to the content type header, it should return JSON
Try setting the 'Accept' header instead.
If I create a JsonFormatter and add it in Application_Start GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonNetFormatter(serializerSettings)); It should do the trick. But I gathered this depreciated as none of the examples are working.
If the accept header of the request is application/xml, content negotiation will still pick the XmlMediaTypeFormatter and will return application/xml. One more thing, the formatter for JSON is called JsonMediaTypeFormatter, and it is already in position 0 of the Formatters collection.

If you only want JSON then clear the formatters collection of all its defaults and then add just the JSON one back in.

You don't need to remove xml support to get JSON response. For GET requests, you should set the Accept-header - not the Content-Type header. For other HTTP verbs, it depends. Fully explained here.
http://blogs.msdn.com/b/kiranchalla/archive/2012/02/25/content-negotiation-in-asp-net-mvc4-web-api-beta-part-1.aspx
Bonus:
Use Google Chrome's Postman plugin to test REST APIs. Highly recommended :)
https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en

You can also write below in GLOBAL.ASAX
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
this also works for me.

Quoting Felipe Leusin (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") );
That makes sure you get json on most queries, but you can get xml when you send text/xml.
If you need to have the response Content-Type as application/json please check Todd's answer below: https://stackoverflow.com/a/20556625/287145

Related

REST api request method input parameters

i've been researching/creating a REST api, in the backbone.js to php context.
i understand the concept of HTTP verbs and when they should be used
GET - select
POST - create
PUT - update
DELETE - delete
i also understand the concept of passing an identifier as a semantic url, e.g.
GET http://api/users/123
DELETE http://api/users/123
in these cases the "123" is the id the business logic will use to get/delete a user.
but what about the POST and PUT contexts? when sending a request to
PUT http://api/users/123
the api will update user id 123 with the supplied parameters, here's where my question arises.
i would assume the input parameters to update with would be sent as PUT parameters. in php syntax this is represented as: file_get_contents('php://input') (this is the same for delete requests.)
when testing this via backbone.js it works perfectly.
but when i try and create a new element with
POST http://api/users/
i would assume the input values would sent as POST parameters/ in php syntax this is represented as $_POST. but this does not work.
after some testing, and reading up on rails style REST apis (which is what the backbone docs suggest), i realized that all request variables are sent the same way. if i change my code to use file_get_contents('php://input') to get the request parameters for every request type, backbone works perfectly.
is this standard fair for REST apis? or just "rails flavored" ones?
PUT, POST, PATCH, etc (everything but GET and DELETE*) accept request bodies. Generally data is passed as either:
A URL encoded string of name/value pairs (exactly the same as a URL querystring) that is decoded and parsed by the server into $_POST (or similar depending on your web framework of choice). This typically relies on the presence of a Content-Type header set to application/x-www-form-urlencoded (browsers do this by default when forms are submitted). If you see the data in file_get_contents('php://input') but not $_POST it's very likely this header is not present or is set to another value. If you're using Chrome, you can see what headers and body the client is sending in the Network tab of the dev tools.
The other popular request body format is to use Content-Type: application/json and then write out a JSON string to the body. This can be accessed via file_get_contents('php://input') and then parsed with a JSON parser.
* Note on DELETE: it's a little unclear whether or not using a request body with DELETE is allowed or a good practice.

XHTTP does not allow Accept header to specify JSON?

I'm hosting a mvc4 REST web api and I have a particular client that is using XHTTP (please don't ask why). However, it turns out that XHTTP is stripping off the "Accept" header and the client is trying to specify the request to come back as json. Unfortunately we dont' get the "Accept" header specified as json and instead return our default javascript format.
I was thinking about a potential workaround whereas they can specify &Accept=JSON in the query string but was wondering if anybody knows anything about XHTTP or how this could be resolved at the XHTTP end and my REST api end?
Thanks!
You could create a HttpMessageHandler that automatically sets the Accept header to application/json if none is provided.

Changing/appending request headers in RESTful API in c#

I have a really weird situation (may be its for me only). I developed a RESTful API. By default it returns the result as JSON/XML/TEXT as per the Content Type sent by the client in headers.
Now client is saying that he wants to set the response as default as XML only. What I mean here is that client will not send any content type in headers and it will by default send the request as XML.
When I access this API from browser, it return it as XML but when client's app requests it, it returns JSON result by default. They are getting the result as XML by putting the content type in headers but they don't want to do it and want to have XML result by default.
I hope I am clear on it. If not please let me know.
Any help would be appreciated. Thanks
[Change]
I am interested in knowing if there is some way I can modify the request headers when I receive request on server.
It is in MVC3, C#.
You can't change the request headers, just query them.
I guess you return your result as a simple string in your controllers, isn't it?
And, you are switching between results depending on the contenttype you read from request, don't you?
What is the contenttype the client call come with?
UPDATE:
Look at this page:
http://aleembawany.com/2009/03/27/aspnet-mvc-create-easy-rest-api-with-json-and-xml/
It's a solution for a previous version of MVC, but it will give you an idea about the solution you need:
Adjust the action result depending on the request contenttype
I find the answer and posting here. I just removed the other return types except the xml type like below:
void ConfigureApi(HttpConfiguration config)
{
// Remove the JSON formatter
config.Formatters.Remove(config.Formatters.JsonFormatter);
// or
// Remove the XML formatter
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
For more details, please follow below link
http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization
Thanks

POST params are empty in Zend_Rest_Controller

I'm using Zend_Rest_Controller to implement a RESTful API.
The GET action works fine, for example when I make the /user/id/1 request the :id parameter is present when I use $request->getParams().
However, when I make a POST request to /user, the postAction() is called just fine but there is no POST data in $request->getParams() or $request->getPost(). $request->getRawBody() shows that they are getting to the server fine though.
Is there any reason why ZF might not be populating the request object with these params? How do I access them?
Double check the content type on the http headers of the request. Should be multipart/form-data.

HttpHeaders in ASP.NET 1.1

How do I read the Response Headers that are being sent down in a page ? I want to be able to read the header values and modify some of them. This is for an ASP.NET 1.1 application but I would be curious to know if it can done in any version of ASP.NET.
The reason for doing this is someone may have added custom headers of their own before the point I am examining the response - so I cannot blindly clear all the headers and append my own - I need to read the all the headers so I can modify the appropriate ones only.
HttpContext.Current.Response (Its a HTTPResponse), exposed ClearHeaders(), AddHeaders() and AppendHeaders().
Not as direct as it is now in later version of ASP.NET, but should be enough to let you modify the headers you wanted to modify.
http://msdn.microsoft.com/en-us/library/system.web.httpresponse_members(VS.71).aspx
AFAIK it cannot be done in ASP.NET 1.1. There is no way for you to get at the response headers - request headers are available but not response headers.
I am not sure if you can do this in other stacks like Java, LAMP though and I am curious to find out...