ASP MVC Return JSON - json

I am working on a web API with ASP.NET MVC (.NET 4.5.2) (I'm quite new to ASP) and I would like the change to response format from my controller to be JSON instead of XML.
I tried several things like using the ActionResult return type and returning something like new Json() but this function is not recognized and Visual Studio asks me to create the function.
I'm not sure I'm giving you enough info to help me, so please ask me for more if necessary :)
Thanks!

All you need to do is this:
[HttpGet]
public object Test(string testparameters)
{
return new {decision = "enable"};
}

If you are making use of an ApiController, the client (probably the browser that makes the HTTP request) should specify which type it is expecting.
When the client sends a request message, it can include an Accept
header. The Accept header tells the server which media type(s) the
client wants from the server. For example:
Accept: text/html,application/xhtml+xml,application/xml
This header tells the server that the client wants either HTML, XHTML,
or XML.
The media type determines how Web API serializes and deserializes the
HTTP message body. Web API has built-in support for XML, JSON, BSON,
and form-urlencoded data, and you can support additional media types
by writing a media formatter.
See Media Formatters in ASP.NET Web API 2.
In your case, your request should contain Accept: application/json

Related

Why not use content negotiation to return JSON object?

I'm using content negotiation to return a JSON object from some WebAPI controllers.
I found this question
How to return Json object on Web API Controller
Here some of the people answered seem to agree that you shouldn't rely on negotiation but should create a new HttpContent class for the JSON return.
Why is this please? As a beginner content negotiation seems to work well.
I have searched for this answer, but can't find an explanation.
ASP.Net Web API in its purest form is intented to create REST ful web services.
As per REST full standards client should have the ability to decide whether the response should be in XML/JSON response. And this can be achieved using Content-negotiation header in the request.
That means your understanding is correct and using Content negotiation you can decide whether you require XML/JSON response in ASP.Net Web API.
If I have to give you example of this then please create web api by default template. This contain value controller.
Now go to chrome browser and request the data and go to IE and request the data. In chrome you will get XML data while in IE you will get JSON data. ( It ask for download json).
Now if you use tool like fiddler and look at request then you will find difference in request header of both browser.
So if you are sure that you always need json data then it is good to return JSON data from controller action it self. If you don't want to do that and still want all your request to be return JSON then please set header "Accept" with application/json.
http://www.asp.net/web-api/overview/formats-and-model-binding/content-negotiation
In short if you want to your api always communicated by json data then it is good to return result of json type rather then depend on content negotiation.

WCF Data Services ODATA throwing error with JSONP

Ok so I have a WCF ODATA service hosted locally for testing purposes. Then I have a Kendo Grid trying to query the service using a Kendo Datasource configured for ODATA exactly like the demo!
On the deployed service, I also implemented the "JSONPSupportBehavior" attribute and class that everyone is talking about!
Still I get this in Fiddler : A supported MIME type could not be found that matches the acceptable MIME types for the request. The supported type(s) 'application/atom+xml;type=feed, application/atom+xml, application/json;odata=verbose' do not match any of the acceptable MIME types 'application/json'
Is this IIS issue now or something else? This is driving me crazy!
This is a change made in the WCF Data Services release. In order to get JSON response back (or JSONP) you need to send Accept header with value application/json;odata=verbose. Pure "application/json" is now reserved for the soon to be coming JSON Light format.
See http://blogs.msdn.com/b/astoriateam/archive/2012/04/11/what-happened-to-application-json-in-wcf-ds-5-0.aspx for more details.

Backbone.js sync using post variables, not json

I'm new to backbone and trying to write an html5 front end for an existing (and pretty big) REST back end. I found that when saving a model, backbone by default sends the model encoded as JSON which my existing API doesn't support.
Is it possible to send plain simple post request with variables using backbone?
I think what you're looking for is Backbone.emulateJSON = true
copied from the official documentation:
If you're working with a legacy web server that can't handle requests
encoded as application/json, setting Backbone.emulateJSON = true; will
cause the JSON to be serialized under a model parameter, and the
request to be made with a application/x-www-form-urlencoded mime type,
as if from an HTML form.

Preventing default views with RESTful api in CakePHP

I am following the tutorial in the CakePHP book that explains the basics of setting up a RESTful web service.
So far, I've updated my routes file to the following:
Router::mapResources('stores');
Router::parseExtensions('json');
I have also setup a blank layout in app/layouts/json and the appropriate json views. I am receiving my json output successfully when I navigate to controller/action.json
I am wondering though, without the.json extension it attempts to load the regular view. I am looking to build a pure api with only json output, is there any way to prevent regular render output instead?
You could force a rendering as JSON if you can recognise a JSON request another way. For example, if the Accepts HTTP header contains application/json, you could put this in your controller:
public function beforeFilter(){
if ($this->request->accepts('application/json')) {
$this->RequestHandler->renderAs($this, 'json');
}
parent::beforeFilter();
}
It's CakePHP 2.0 notation, but something similar probably exists for CakePHP 1.2 and 1.3.
You could also detect the request Content-Type instead, or as well, especially if Accepts is not used.
What are you seeing at the moment? If you've used bake Cake may have generated the views for you?
Just delete the views in /app/views/layout and /app/views/controllername
If you are trying to prevent the request from hitting the controller at all then I'm not so sure, you could just update your .htaccess file to only send requests ending in .json to the app or something similar.
here is what i did.
if i know i'm building only json API, i added to my AppController.php following:
public function beforeFilter()
{
if (empty($this->request->params['ext']) || $this->request->params['ext'] != "json")
{
$this->render(FALSE, 'maintenance'); //no view, only layout
$this->response->send();
$this->_stop();
}
}
and in my /app/Layouts/maintenance.ctp
echo __('Invalid extension');
this way all requests without the json extension will end up on the "maintenance" page where you can put any info you want, i'm planning to put there link to API docs.

Mimetypes for a RESTful API

The Sun Cloud API at http://kenai.com/projects/suncloudapis/pages/Home is a good example to follow for a RESTful API. True to RESTful principles, when you GET a resource you get no more nor less than a representation of that resource.
The Content-Type header in the response tells you exactly what the type of that resource is, for example application/vnd.com.sun.cloud.Snapshot+json. Sun has registered these mimetypes with the IANA.
How practical is this in general currently? Most API's I have seen have used the Content-Type of "application/json". This tells you that the response is JSON but nothing more about it. You have to have something in the JSON object, like a "type" property, to know what it is.
I'm designing a RESTful API (which will not be made public, therefore I wouldn't be registering mimetypes). I have been using RESTEasy and I find that even if I specify a complete mimetype, the Content-Type in the response header will be exactly what the Accept request header specified. If the request asks for "application/*+json" by default the response header will have "application/*+json". I can probably fix this by changing the header before the response goes out, but should I try to do that? Or should the response have a wildcard just like the request did?
Or should I just serve up "application/json" like most APIs seem to do?
Additional thoughts added later:
Another way of stating the question is: Should I use HTTP as the protocol, or should I use HTTP only as a transport mechanism to wrap my own protocol?
To use HTTP as the protocol, the entity body of the response contains the representation of the object requested (or the representation of an error message object), the "Content-Type" header contains the exact type of the object, and the "Status" header contains a success or error code.
To use HTTP as merely a transport mechanism, the "Status" header is always set to 200 OK, the "Content-Type" is something generic like "application/json", and the entity body contains something that itself has an object, an object type, an error code and whatever else you want. If your own protocol is RESTful, then the whole scheme is RESTful. (HTTP is a RESTful protocol but not the only possible one.)
Your own protocol will be opaque to all the transport layers. If you use HTTP as the protocol, all the transport layers will understand it and may do things you don't want; for instance a browser will intercept a "401 Unauthorized" response and put up a login dialog, even if you want to handle it yourself.
I use my own vnd.mycompany.mymediatype+xml media types for many of my representations. On the client I dispatch to the appropriate controller class based on the media type of the returned representation. This really allows the server to control the behavior of my client application in response to the user following a link.
Personally, I believe that using application/xml and application/json are one of the worst choices you can make if you hoping to support REST clients. The only exception to this is when the client only uses downloaded code (like Javascript) to interpret the data.
Or should I just serve up "application/json" like most APIs seem to do?
I don't think so.
A media type is the only point of coupling between your RESTful web application and the clients that use it. The documentation of your media types is the documentation of your API. Your media types are the contract between your clients and your application. Eliminate the specific media type and you eliminate an important element that makes REST workable.
Sun has registered these mimetypes with the IANA.
Couldn't find any mention of that here. AFAIK, there is no requirement to actually register your custom media type with the IANA. The convention seems to be to use the inverted domain notation of application/vnd.com.example.app.foo+json, which prevents namespace conflicts. If and when your media type becomes stable and public, it might be a good idea, but there's no requirement. Could be wrong on this, though.
Will you get any value by specifying a complete mimetype? Would you do anything with the complete mimetype different than you would if the mimetype was application/json?
My 2 cents- If the API is not going to be made public, then I see no reason for a complete mimetype. A mimetype of application/json should be more than enough. You already know the type of json that the response is returning. If the API eventually becomes public, then worry about a complete mimetype... or just let people figure it out.