Click here to Skip to main content
11,577,905 members (61,712 online)
Click here to Skip to main content

JSONP in ASP.NET Web API Quick Get Started

, 4 Aug 2013 CPOL 27.6K 14
Rate this:
Please Sign up or sign in to vote.
This tip contains the basic introduction to the JSONP, Same-Origin and Cross-Origin Resource Sharing concepts and quick get started with JSONP in ASP.NET Web API.

Introduction

While searching the web to get started with JSONP in ASP.NET Web API, I was not able to find a real quick start guide. Rather, I found many discussions and detailed articles. So I thought of collating the information from across the web to provide a real simple quick start guide on JSONP in ASP.NET Web API for beginners.

Background

This is a quick get started with JavaScript Object Notation with Padding (JSONP) in ASP.NET Web API to get data from different domains and also explain about the JSONP, Same-Origin and Cross-Origin Resource Sharing concepts.

Same-Origin Policy Vs. Cross-Origin Resource Sharing (CORS)

Same-origin policy is a concept in browser-side programming languages (such as JavaScript) which allows accessing resources in the same site (same domain) but preventing accessing resources in different domains.

Cross-origin resource sharing (CORS) is a mechanism that allows JavaScript on a web page to make XMLHttpRequests to another domain, not the domain the JavaScript originated from. Such "cross-domain" requests would otherwise be forbidden by web browsers, per the same origin security policy. CORS defines a way in which the browser and the server can interact to determine whether or not to allow the cross-origin request.

What and Why JSONP?

AJAX (XMLHttpRequest) doesn’t allow cross domain communication due to security reasons. JavaScript Object Notation with Padding (JSONP) is a way to grab JSON data from external domains. It’s a better and cleaner alternative to other approaches (web proxy and IFrame) to get data from an external domain / CORS (Cross-Origin Resource Sharing).

References

JSONP (JavaScript Object Notation with Padding) = JSON data padded with JavaScript function name

callbackFunc({ "firstName": "Sathik Ali", "lastName": "S" }); 

Enable AJAX Request to Get JSONP Data

We need to set callback and data type attributes of Ajax request as highlighted below:

<script type="text/javascript">
$("#getJsonp").click(function () {
$.ajax({
       	type: 'GET',
              url: "http://localhost:5511/api/values/GetUserName/1",
              callback: 'callbackFunc',
              contentType: "application/json",
              dataType: 'jsonp'
              })
});
 
function callbackFunc(resultData) {
alert(resultData);
}
</script>

Enable ASP.NET Web API to Return JSONP Data

  1. Install the JSONP MediaTypeFormatter by entering the following command using NuGet Package Manager console in Visual Studio.
    Install-Package WebApiContrib.Formatting.Jsonp
    
  2. Add a FormatterConfig class in App_Start folder:
        public class FormatterConfig
        {
            public static void RegisterFormatters(MediaTypeFormatterCollection formatters)
            {
                var jsonFormatter = formatters.JsonFormatter;
                jsonFormatter.SerializerSettings = new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                };
     
                // Insert the JSONP formatter in front of the standard JSON formatter.
                var jsonpFormatter = new JsonpMediaTypeFormatter(formatters.JsonFormatter);
                formatters.Insert(0, jsonpFormatter);
            }
        }
  3. Add the following routes in /App_Start/RouteConfig.cs:
    routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}/{format}",
                    defaults: new { id = RouteParameter.Optional, format = RouteParameter.Optional }
                );
  4. Add the following line in the Application_Start method of Global.ascx.cs:
    FormatterConfig.RegisterFormatters(GlobalConfiguration.Configuration.Formatters);

Points of Interest

If you want your routes mapping with action, please specify the following in App_Start/RouteConfig.cs:

routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}/{format}",
                defaults: new { id = RouteParameter.Optional, format = RouteParameter.Optional }
            );

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

S.Sathik Ali
Technical Lead
India India
No Biography provided

You may also be interested in...

Comments and Discussions

 
Questionswitch between formatters Pin
Alfredo Andino3-Jul-15 4:59
memberAlfredo Andino3-Jul-15 4:59 
GeneralMy vote of 5 Pin
Member 1071222928-Feb-15 8:13
memberMember 1071222928-Feb-15 8:13 
SuggestionFix for 'System.Web.Http.GlobalConfiguration.get_Configuration()' error Pin
Rudy Otzen6-Jan-15 23:39
memberRudy Otzen6-Jan-15 23:39 
GeneralRe: Fix for 'System.Web.Http.GlobalConfiguration.get_Configuration()' error Pin
S.Sathik Ali8-Jan-15 2:03
memberS.Sathik Ali8-Jan-15 2:03 
GeneralMy vote of 5 Pin
fmtoro25-Jun-14 9:24
memberfmtoro25-Jun-14 9:24 
GeneralRe: My vote of 5 Pin
S.Sathik Ali26-Jun-14 19:59
memberS.Sathik Ali26-Jun-14 19:59 
QuestionOnce again Pin
fmtoro25-Jun-14 9:22
memberfmtoro25-Jun-14 9:22 
QuestionMost valuable article Pin
softsathian21-Apr-14 18:34
membersoftsathian21-Apr-14 18:34 
AnswerRe: Most valuable article Pin
S.Sathik Ali23-Apr-14 17:45
memberS.Sathik Ali23-Apr-14 17:45 
QuestionAwesome article Pin
codeprojecthai2-Mar-14 12:07
membercodeprojecthai2-Mar-14 12:07 
GeneralMy vote of 5 Pin
manoj.jsm4-Aug-13 23:29
membermanoj.jsm4-Aug-13 23:29 
Hi Bro,
It's informative and nice
GeneralRe: My vote of 5 Pin
S.Sathik Ali5-Aug-13 8:14
professionalS.Sathik Ali5-Aug-13 8:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150603.1 | Last Updated 4 Aug 2013
Article Copyright 2013 by S.Sathik Ali
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid