Cross-domain access to instance code in asp.net WebResponse

Source: Internet
Author: User
Tags json

  A long time ago, a friend wrote a asp.net. WebResponse access to Cross-domain examples, I turn to learn together with you, I hope the article will help you.

Two days ago, a friend asked me to help him write such a program: ASP.net inside the page to visit the ASP, the data submitted to the other side of the database, according to the return value (the return value is: OK or error), if the OK and then fill in the local database. At that time, take for granted, feel very simple, with JS XMLHTTP, if according to the value of response is "OK" on the implementation of the submit local database. Soon finished writing out the past, let a friend try, a try to find no, then a ask, the original is Cross-domain access, I have neglected, so let friends to change the ASP to Web service, can be friends that the program is a cooperative company to do, only ASP, will not use the Web service, crazy halo ing. No way, can only please out of the asp.net WebResponse, a lot of Web site acquisition program is using this. The first edition is finished, but can be accessed across the domain, but garbled, adjust the encoding of the way, finally can be. This application is small but involves a lot of knowledge:   1, XMLHTTP can not be submitted across the domain.   Of course XMLHttpRequest or expedient solution,   2, WebResponse can do cross-domain access, but note   1), get and post differences. 2), pay attention to the problem of timeout.   These are simple procedures, write down the memo, the master will not have to see.   No nonsense, the following is the relevant C # code:     Code as follows:///<summary>        ///use post method to send data        ///</summary>      ///<param name= "Pi_strposturl"   Submit address > & nbsp      ///<param name= "pi_strparm" > Parameters </param>        ///<returns>& lt;/returns>                public static string Postresponse (StrinG Pi_strposturl, String pi_strparm)         {            try   &NB Sp         {               //code         &NB Sp       Encoding t_encoding = encoding.getencoding ("GB2312");          Uri T_uri = n EW Uri (Pi_strposturl);                               byte[] Parambytes = T_encoding.getbytes (Pi_strparm);                 WebRequest t_webrequest = WebRequest.Create (T_uri);         t_webrequest.timeout = 100000;                /Set contenttype               & nbsp T_webrequest.contenttype = "application/x-www-form-urlencoded";                   T_webrequest.method = ENumMethod.POST.ToString ();                //initialization                 using (Stream T_restream = T_webrequest.getrequeststream ())                 {  &N Bsp                //Send data                 &NB Sp   requestStream.Write (parambytes, 0, parambytes.length);                                   W Ebresponse t_webresponse =  t_webrequest.getresponse ();                   using (StreamReader T_streamreader = new StreamReader (t_web Response. GetResponseStream (), t_encoding))                 {        &N Bsp           return t_streamreader.readtoend ();       &NBsp        }             {            catch             {                return "ERROR";             {       }   public static string GetResponse (String PI_STRP Osturl, String pi_strparm)                     try     &NBSP ;       {               //encoding           &NB Sp     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_web Response.getresponsestream (), t_encoding))                 {                    return t_streamreader.readtoend ();                            }             catch (Exception e)             {    &NBSP           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.quer Y              if (Parmstring.startswith ("?"))                     T_parm = T_parm. Remove (0, 1);                              t_strurlpath = "HT tp://"+ T_url. Authority + T_url. absolutepath;      &nbsP       return GetResponse (T_strurlpath, T_parm, Pi_method);        }  public enum Enummethod         {        &NBSP ;   POST,             get             now jquery Ajax supports Cross-domain, Here's an example where we can process the above JSON data   Jquery.getjson also support the JSONP data method invocation.   Client Jquery.ajax Call code example:     code is as follows: $.ajax ({ type: "Get",  async:false,  url: "http://www.") Jb51.net/ajax.do ",  datatype:" Jsonp ",  jsonp:" Callbackparam ",//server used to receive callback call function name parameters   Jsonpcallback: "Success_jsonpcallback",//callback function name  success:function (JSON) {  alert (JSON);   Alert (json[0].name); &NBSP},  error:function () {  alert (' fail ');  });       Service-side return Data sample code:     Code as follows: public void ProcessRequest (HttpContext context) { context. Response.ContentType = "Text/plain";  string CAllbackfunname = context. request["Callbackparam"];  context. Response.Write (Callbackfunname + "([{Name:" John "}])"); The principles of the     jquery.getscript approach are similar, and they also require support on the server-side return data, unlike the results returned by the server. Instead of returning a function call to a callback, the result is assigned directly to the variable name that the request passes. The client loads the returned data as if an external script was 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.