Posts tagged with 'JSON'
I have a web page on domain A and, say, a Json endpoint on domain B. I would like domain A to make an Ajax request to domain B, but when I try that, I get an error message, as shown here:
Some options:
- Make the request server-side instead of client side.
- If you have control of the endpoint, add "Access-Control-Allow-Origin" to the response header.
- Use jsonp (you may still need control of the endpoint if it doesn't support jsonp already).
Let's explore the jsonp option. Here's a similar request to the one above, except this time it's using jsonp.
It does not raise an error.
The way jsonp works is a little wacky, but the main thing you need to know is that you need to specify a callback function. jQuery handles this automatically on the client side. Here's how I handle it on the server side with ASP.NET MVC using the Mvc.Jsonp package.
Notice three things:
- SomeController inherits from JsonpControllerBase
- GetAllItems return type is JsonpResult and has a "callback" string parameter
- The Jsonp function from the base class and how callback is passed to it.
The benefit is that you can now do cross-domain scripting. So far the drawbacks seems to be that:
- It's limited to GET requests
- Error handling may take some extra work
- If there is no Jsonp endpoint, then you either have to make one or you're out of luck.
I'm giving it a shot on Ledger, and seems to be working fine so far.
I've been working a little bit here and there on a mobile app. One thing this app does a lot is use a RESTful API over HTTP, where the results are JSON.
I'm using RestSharp to handle these requests, and RestSharp can automatically serialize Json results into C# object(s), assuming I have C# objects that match.
Well, some of these JSON results can be a little complex. Not terribly complex, mind you, but enough to where it's annoying to create the classes myself. But I thought to myself, maybe there's a tool out there that already does this for me. I googled around and found json2csharp, which is a handy web app that does exactly that.
Well, thanks to Rob Gibbens, I now know that this feature is actually built-in to Visual Studio 2013, and available for 2012 as part of "ASP.NET and Web Tools".
You can see that there are some differences, but these tools get you most of the way there!