CORS Security, and Allowing JSONP Responses from Web API

Printer-friendly version

When building a Web API project, you need to keep in mind how requests to your methods will be made. If requests are made client-side, you'll need to take CORS (Cross-Origin Resource Sharing) security into consideration. This can be done a few ways, which I won't get into for the sake of this post, but you can find more information about CORS here.

One of the ways to get around cross-origin restrictions is to use JSONP (JSON with Padding). Instead of an XMLHTTPRequest, an AJAX request using JSONP injects a <script> tag on the page with the src value set to the target URL. The response object is passed as an argument to the specified callback function, and from there you can do whatever with your data. Because of how this works, JSONP only works for GET requests.

Now, back to Web API. By default, if you attempt to call a method using JSONP, you aren't going to get your expected response, and the only reason for this is because out-of-box, Web API responses aren't formatted for JSONP. Luckily, there is a really simple fix, and that is to install the WebApiContrib.Formatting.Jsonp nuget package and implement the JSONP Formatter. Once you have the package installed, you can implement it in your Global.asax.cs file by adding the following to Application_Start():

GlobalConfiguration.Configuration.AddJsonpFormatter(GlobalConfiguration.Configuration.Formatters.JsonFormatter, "callback");

When you make your request, just be sure to specify "jsonp" as your data type, and you're good to go:

$.ajax({

url: "/api/Docs/GetAllRecords",

dataType: "jsonp",

success: function (docs) {

DoSomething(docs);

},

error: function (data) {

DoSomethingElse(data);

}

});

 

About the Author:

TopLine Strategies delivers the complete integration and development of sales, marketing and customer service technologies that enable corporate clientele to improve revenue streams and strengthen customer interactions. Our project management and consulting is designed to achieve timely delivery, 100 percent user adoption of the technologies we implement and deliver measurable returns on investments for our clients.

Comments (0)

Related Blogs

If you’ve spent any time developing with the CRM mobile app, you know how frustrating it can be when trying to track down bugs.

A while back I had set up a Hyper-V virtual machine, but it had been a while since I've needed to use it again. The time came again recently as I needed a VM to do some OS-specific testing.

Have you given your independent sales reps CRM licenses so they can access CRM directly, rather than going throug

Whether you’re a user that just wants to share a view with someone or you’re an administrator/manager that would like to create and distribute personalized views, sharing personal views is a very c