asp.net webresponse cross-domain access to instance code _ practical Tips

Source: Internet
Author: User

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 cannot be committed across domains.

Of course, XMLHttpRequest or expedient solutions,

2. WebResponse can be accessed across domains, but be aware

1. The difference between get and post.
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:

Copy Code code as follows:

<summary>
Sending data using the Post method
</summary>
<param name= "Pi_strposturl" > Submit address </param>
<param name= "Pi_strparm" > Parameters </param>
<returns></returns>
public static string Postresponse (String Pi_strposturl, String pi_strparm)
{
Try
{
Coding
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 (); Class
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
{
Coding
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 that jquery Ajax supports Cross-domain, here's an example where we can process the above into JSON data

The Jquery.getjson also supports the JSONP data method invocation.

Sample call code for client Jquery.ajax:

Copy Code code as follows:

$.ajax ({
Type: "Get",
Async:false,
URL: "Http://www.jb51.net/ajax.do",
DataType: "Jsonp",
JSONP: "Callbackparam",//The parameter of the function name used by the server to receive the callback call
Jsonpcallback: "Success_jsonpcallback",//callback's function name
Success:function (JSON) {
alert (JSON);
alert (json[0].name);
},
Error:function () {
Alert (' fail ');
}
});

Sample code for server-side return data:

Copy 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 jquery.getscript approach is similar in that it requires server-side return data support, and different results from server-side returns. 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.