当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net中WebResponse 跨域访问实例代码

asp.net中WebResponse 跨域访问实例代码

2017年12月12日  | 移动技术网IT编程  | 我要评论

万豪移民,米乐圈,永远的微笑吉他谱

前两天,一个朋友让我帮他写这样一个程序:在asp.net里面访问asp的页面,把数据提交对方的数据库后,根据返回的值(返回值为:ok或error),如果为ok再把填入本地数据库。当时,想当然,觉得很简单,用js的xmlhttp ,如果根据response 的值是“ok”就执行提交本地数据库。很快写完发过去,让朋友试试,一试发现不行,后来一问,原来是跨域访问,我给忽略了,于是让朋友把asp改成web service,可朋友说程序是合作公司做的,只会asp,不会用web service ,狂晕ing。没办法,只能请出asp.net的 webresponse了,很多网站采集程序都是用这个。第一版写完了,倒是可以跨域访问了,不过是乱码,调整有关编码的方式,终于可以了。这个应用虽小可是涉及的知识点不少:

1、xmlhttp 不能跨域提交。

当然xmlhttprequest还是权宜的解决的方法,

2、webresponse可以进行跨域访问,不过要注意

1)、get和post的区别。
2)、注意timeout的问题。

这些都是简单的程序,记下来备忘,高手就不必看了。

不废话了,下面是相关的c#代码:

复制代码 代码如下:

/// <summary>
        /// 使用post方法发送数据
        /// </summary>
        /// <param name=”pi_strposturl”>提交地址</param>
        /// <param name=”pi_strparm”>参数</param>
        /// <returns></returns>      
        public static string postresponse(string pi_strposturl, string pi_strparm)
        {
            try
            {
                //编码
                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;
                //设置contenttype
                t_webrequest.contenttype = “application/x-www-form-urlencoded“;

                t_webrequest.method = enummethod.post.tostring();                //初始化
                using (stream t_restream = t_webrequest.getrequeststream())
                {
                    //发送数据
                    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 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
        }

现在jquery ajax支持跨域了,下面看个实例我们可对上面进行处理成json数据即可

jquery.getjson也同样支持jsonp的数据方式调用。

客户端jquery.ajax的调用代码示例:

复制代码 代码如下:

$.ajax({
 type : "get",
 async:false,
 url : "//www.jb51.net/ajax.do",
 datatype : "jsonp",
 jsonp: "callbackparam",//服务端用于接收callback调用的function名的参数
 jsonpcallback:"success_jsonpcallback",//callback的function名称
 success : function(json){
  alert(json);
  alert(json[0].name);
 },
 error:function(){
  alert('fail');
 }
});

服务端返回数据的示例代码:

复制代码 代码如下:

public void processrequest (httpcontext context) {
 context.response.contenttype = "text/plain";
 string callbackfunname = context.request["callbackparam"];
 context.response.write(callbackfunname + "([ { name:"john"}])");
}

而jquery.getscript方式处理的原理类似,也同样需要服务端返回数据上做支持,不同的是服务端返回的结果不同。不是返回一个callback的function调用,而是直接将结果赋值给请求传递的变量名。客户端则是像引入一个外部script一样加载返回的数据。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网