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

TheReact Native Open Source roadmap was announced in Q4 2018 after they decided to invest more in the React Native open source community.

October is not just about pumpkins, fall foliage, and cooler temps anymore. October 2018 also means the exciting introduction of Microsoft Dynamics 365 for Customer Engagement.

Back in 2016, Microsoft introduced its intentions to refresh its CRM and ERP strategy with Dynamics 365. At the heart of its services was the Common Data Model (CDM).