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

I have been doing a lot of custom workflow steps lately for MS CRM.

Would you like to use Power BI to build data visualizations around your Visual Studio Team Services user stories, test cases and test results?

A handy new feature introduced with C# 7 is Local Functions. As an example, in the LINQ query below, the select method is bit hard to read and can be simplified using a helper function.

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