ShareThis

Cross Domain Access to HTTP Handler using jQuery Ajax

We can access Http handlers directly from a regular AJAX call, if they are in the same domain. However it is not the case if handler is hosted in a different domain. One solution is to use JSONP (the “padding” around the pure JSON).

JSONP pass the response from the server in to a user specified function, return the response as JSON, but also wrap the response in the requested call back.

In order to use JSONP, server has to support JSONP. The client tells the server the callback function for the response. The server then return the response as JSON, but also wraps the response in this callback function.

HttpHandler sending the response in the format expected by JSONP.

public class AtomHandler : IHttpHandler
{
  ///<summary>
  /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the System.Web.IHttpHandler interface.
  ///</summary>
  /// <param name="context"> A System.Web.HttpContext object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests .< /param>
  public voidProcessRequest( HttpContext context)
  {
   string jsonString= "{'Title':'What Will Brand Engagement Look Like in 2020?','Summary':'When it comes to brand engagement, 5 years will seem like a lifetime.','UpdatedDate':'4/23/2015 4:27:46 AM +00:00','FeedType':'MBD - Marketing'}" ;
 
   string jsonp=context.Request["callback"];
 
   if (! String.IsNullOrEmpty (jsonp))
   {
    jsonString = jsonp + "("+jsonString+")";
   }
 
   context.Response.ContentType = "application/json";
   context.Response.Write(jsonString);
  }
 
  ///<summary>
  /// Gets a value indicating whether another request can use this instance.
  ///</summary>
  public bool IsReusable
  {
   get
   {
    return false;
   }
  }
}


jQuery JSONP request to get data from handler.

var loadAtomData=function() {
  try {
    $.ajax({
      url: "http://<server>/AtomTest/AtomHandler.ashx",               
      type: "GET",
      dataType: "jsonp",
      jsonp: "callback",
      contentType: "application/json; charset=utf-8" ,
 
      success: function (responseData, txtStatus, jqXHR) {
        console.log( "The response is" , responseData);
      },
      error: function (responseData, txtStatus, errThrown) {
        console.warn(responseData, txtStatus, errThrown);
        alert( 'JSONP failed - ' + txtStatus);
      }
    });
  } catch(e) {
    alert(e)
  }
}
 
$(document).ready( function() {
loadAtomData();
});

Web browsers let scripts from a webpage to access data from a second page, if both have the same origin (URI scheme, hostname and port). JSONP works since browsers do not enforce the same-origin policy on <script> tags.

0 comments: