Asp.net MVC3 implements JSONP

Source: Internet
Author: User

JSONP can help us solve cross-origin access problems. JSONP is JSON With Padding. Here we will not explain its principle. Let's look at how ASP. net mvc 3 is implemented. First, we need to define a JsonpResult. The code is like this and directly inherited from JsonResult, override the ExecuteResult Method
 
Public class JsonpResult: JsonResult
{
Private static readonly string JsonpCallbackName = "callback ";
Private static readonly string CallbackApplicationType = "application/json ";

/// <Summary>
/// Enables processing of the result of an action method by a custom type that inherits from the <see cref = "T: System. Web. Mvc. ActionResult"/> class.
/// </Summary>
/// <Param name = "context"> The context within which the result is executed. </param>
/// <Exception cref = "T: System. ArgumentNullException"> The <paramref name = "context"/> parameter is null. </exception>
Public override void ExecuteResult (ControllerContext context)
{
If (context = null)
{
Throw new ArgumentNullException ("context ");
}
If (JsonRequestBehavior = JsonRequestBehavior. DenyGet )&&
String. Equals (context. HttpContext. Request. HttpMethod, "GET "))
{
Throw new InvalidOperationException ();
}
Var response = context. HttpContext. Response;
If (! String. IsNullOrEmpty (ContentType ))
Response. ContentType = ContentType;
Else
Response. ContentType = CallbackApplicationType;
If (ContentEncoding! = Null)
Response. ContentEncoding = this. ContentEncoding;
If (Data! = Null)
{
String buffer;
Var request = context. HttpContext. Request;
Var serializer = new JavaScriptSerializer ();
If (request [JsonpCallbackName]! = Null)
Buffer = String. Format ("{0} ({1})", request [JsonpCallbackName], serializer. Serialize (Data ));
Else
Buffer = serializer. Serialize (Data );
Response. Write (buffer );
}
}
}

Then, a simple extension method is defined:
Public static class ContollerExtensions
{
/// <Summary>
/// Extension methods for the controller to allow jsonp.
/// </Summary>
/// <Param name = "controller"> The controller. </param>
/// <Param name = "data"> The data. </param>
/// <Returns> </returns>
Public static JsonpResult Jsonp (this Controller controller, object data)
{
JsonpResult result = new JsonpResult ()
{
Data = data,
JsonRequestBehavior = JsonRequestBehavior. AllowGet
};

Return result;
}
}

Use it in the Controller. Our Controller is called ApiController, and the Action:
 
/// <Summary>
/// Get some basic information with a jsonp get request.
/// </Summary>
/// <Remarks>
/// Sample url:
/// Http: // localhost: 50211/Api/GetInformation? Key = test & callback = json123123
/// </Remarks>
/// <Param name = "key"> key </param>
/// <Returns> JsonpResult </returns>
Public JsonpResult GetInformation (string key)
{
Var resp = new Models. CustomObject ();
If (ValidateKey (key ))
{
Resp. Data = "You provided key:" + key;
Resp. Success = true;
}
Else
{
Resp. Message = "unauthorized ";
}

Return this. Jsonp (resp );
}

Private bool ValidateKey (string key)
{
If (! String. IsNullOrEmpty (key ))
Return true;
Return false;
}
 
The above method receives a string parameter, then we add a prefix string before it, and the return Result is Jsonp Result.

Model for passing values:
Public class CustomObject
{
Public bool Success {get; set ;}
Public object Data {get; set ;}
Public string Message {get; set ;}
}


Run WebSite and access http: // localhost: 50211/Api/GetInformation? Callback = myfunction & key = haha
We can see the following results:
Myfunction ({"Success": true, "Data": "You provided key: haha", "Message": null })
 
Okay. Now let's use it in another site:
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> Index </title>
<Script src = ".../Scripts/jquery-1.4.1.min.js" type = "text/javascript"> </script>
<Script type = "text/javascript">
$ (Document). ready (function (){
$ ('. Result'). hide ();

$ ('# Test'). click (function (){
$ ('. Result'). fadeOut ('quick ');
Certificate ('.result'{.html ('');

$. Ajax ({
Url: 'http: // localhost: 50211/Api/getinformation ',
Data: {key: $ ('input [name = key] '). val ()},
Type: "GET ",
DataType: "jsonp ",
JsonpCallback: "localJsonpCallback"
});
});
});

Function localJsonpCallback (json ){
// Do stuff...
If (json. Success ){
Certificate ('.result').html (json. Data );
}
Else {
Response ('.result'{.html (json. Message );
}

$ ('. Result'). fadeIn ('quick ');
}
</Script>
</Head>
<Body>
<Div>
Enter key: <input type = "text" name = "key" value = "some data key, this parameter is optional"/>
<Br/> <input type = "button" value = "Test JSONP" id = "test"/>
<Div class = "result">
</Div>
</Div>
</Body>
</Html>

JQuery Ajax is used to call it here. If you are familiar with JQuery, you should be able to understand it. The result is that the div displays a string under the button:

You provide key: some data key, this parameter is optional
You can also use the getJSON method here.
Okay, that's easy. Hope to help your Web development.

 

 

Author: Petter Liu

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.