Tuesday, April 8, 2014

JSONP calls in ASP.NET MVC

JSONP is "JSON with padding".  It is used to access or transfer data across the domains.  The code below is used to access JSONP data from a remote server and fetch the results in ASP.NET MVC

public ContentResult FetchData()
        {
            string signedUrl = ""; //URL to fetch jsonp data from
            WebRequest request = (HttpWebRequest)WebRequest.Create(signedUrl);
            request.Method = WebRequestMethods.Http.Get;
            string result = string.Empty;

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    result = reader.ReadToEnd();
                }
            }

            return Content(result, "application/javascript");
        }

No comments: