Example of WebResponse cross-origin access in asp.net

Source: Internet
Author: User
Tags json

Two days ago, a friend asked me to write such a program for him: Access the asp page in asp.net, submit the data to the database of the other party, and then return the returned value (return value: OK or ERROR ), if it is OK, enter the local database. At that time, I thought it was very simple. I used js xmlhttp. If the value of response is "OK", I would submit it to the local database. Soon I wrote it and sent it to my friend. I tried it and found that it didn't work. Then I asked my friend to change asp to web service, but a friend said that the program is done by a partner company, only asp will be used, and web service will not be used. No way, you can only ask for the asp.net WebResponse. This is used by many website collection programs. After the first version is completed, it can be accessed across domains, but it is garbled and the encoding method is adjusted. This application is small but involves many knowledge points:

1. xmlhttp cannot be submitted across domains.

Of course, XMLHttpRequest is an appropriate solution,

2. webresponse can be used for cross-origin access. Note that

1) difference between get and post.
2) pay attention to the Timeout problem.

These are simple programs, so you don't have to read them.

The following is the relevant c # code:

 

The code is as follows: Copy code
/// <Summary>
/// Use the Post method to send data
/// </Summary>
/// <Param name = "pi_strPostURl"> submit address </param>
/// <Param name = "pi_strParm"> parameter </param>
/// <Returns> </returns>
Public static string PostResponse (string pi_strPostURl, string pi_strParm)
        {
Try
            {
// Encoding
Encoding t_Encoding = Encoding. GetEncoding ("GB2312");
Uri t_Uri = new Uri (pi_strPostURl );
Byte [] paramBytes = t_Encoding.GetBytes (pi_strParm );
WebRequest t_WebRequest = WebRequest. Create (t_Uri );
T_WebRequest.Timeout = 100000;
// Set ContentType
T_WebRequest.ContentType = "application/x-www-form-urlencoded";
               
T_WebRequest.Method = EnumMethod. POST. ToString (); // Initialization
Using (Stream t_REStream = t_WebRequest.GetRequestStream ())
                {
// Send data
RequestStream. Write (paramBytes, 0
, ParamBytes. Length );
                }
               
WebResponse t_WebResponse =
T_WebRequest.GetResponse ();
               
Using (StreamReader t_StreamReader = new StreamReader (t_WebResponse. GetResponseStream (), t_Encoding ))
                {
Return t_StreamReader.ReadToEnd ();
                }
            }
Catch
            {
Return "ERROR";
            }
        }
 
Public static string GetResponse (string pi_strPostURl, string pi_strParm)
        {
Try
            {
// Encoding
Encoding t_Encoding = Encoding. GetEncoding ("GB2312");
Uri t_Uri = new Uri (string. Format ("{0 }? {1} ", pi_strPostURl, pi_strParm ));
               
WebRequest t_WebRequest =
WebRequest. Create (t_Uri );
              
T_WebRequest.Timeout = 100000;
T_WebRequest.ContentType = "application/x-www-form-urlencoded";
              
T_WebRequest.Method = EnumMethod. GET. ToString ();
WebResponse t_WebResponse =
T_WebRequest.GetResponse ();
               
Using (StreamReader t_StreamReader = new StreamReader (t_WebResponse.GetResponseStream (), t_Encoding ))
                {
Return t_StreamReader.ReadToEnd ();
                }
            }
Catch (Exception e)
            {
Return e. ToString ();
            }
        }
Public static string AtionResponse (string pi_Url, EnumMethod pi_Method)
        {
String t_strUrlPath = "";
String t_parm = "";
Uri t_Url = new Uri (pi_Url );
T_parm = t_Url.Query;
If (parmString. StartsWith ("? ")
T_parm = t_parm.Remove (0, 1 );
T_strUrlPath = "http: //" + t_Url. Authority + t_Url. AbsolutePath;
Return GetResponse (t_strUrlPath, t_parm, pi_Method );
        }
Public enum EnumMethod
        {
POST,
GET
        }

Now jquery ajax supports cross-origin. Let's take a look at the example below and process the above as json data.

JQuery. getJSON also supports jsonp data calling.

Sample code for calling the client JQuery. ajax:

The code is as follows: Copy code

$. Ajax ({
Type: "get ",
Async: false,
Url: "http://www.xxx.com/ajax.do ",
DataType: "jsonp ",
Jsonp: "callbackparam", // parameters of the function name used by the server to receive callback calls
JsonpCallback: "success_jsonpCallback", // callback function name
Success: function (json ){
Alert (json );
Alert (json [0]. name );
},
Error: function (){
Alert ('fail ');
 }
});

Sample Code of the data returned by the server:

The code is as follows: Copy code
Public void ProcessRequest (HttpContext context ){
Context. Response. ContentType = "text/plain ";
String callbackFunName = context. Request ["callbackparam"];
Context. Response. Write (callbackFunName + "([{name:" John "}])");
}

The processing principle of jquery. getScript is similar. It also requires support for data returned by the server. The difference is that the results returned by the server are different. Instead of returning a callback function call, the result is directly assigned to the variable name passed in the request. The client loads the returned data just like an external script is introduced.

 

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.