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

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

I was recently working with integrating CRM and SharePoint using integration in a plugin/custom workflow assembly following the ideas outlined

Do you have a global software development team? Do tasks get passed daily from work site to work site around the world?

While working in Dynamics CRM, I needed to add several options to a few different optionsets on the Lead entity.