惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
Darknet – Hacking Tools, Hacker News & Cyber Security
NISL@THU
NISL@THU
S
Securelist
O
OpenAI News
S
Security Affairs
Cyberwarzone
Cyberwarzone
T
Threatpost
Simon Willison's Weblog
Simon Willison's Weblog
The Last Watchdog
The Last Watchdog
L
LINUX DO - 最新话题
C
Cisco Blogs
PCI Perspectives
PCI Perspectives
SecWiki News
SecWiki News
S
Secure Thoughts
GbyAI
GbyAI
I
Intezer
AWS News Blog
AWS News Blog
F
Fortinet All Blogs
I
InfoQ
阮一峰的网络日志
阮一峰的网络日志
Google Online Security Blog
Google Online Security Blog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
A
About on SuperTechFans
S
Schneier on Security
P
Proofpoint News Feed
雷峰网
雷峰网
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
小众软件
小众软件
H
Heimdal Security Blog
Microsoft Security Blog
Microsoft Security Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
The Exploit Database - CXSecurity.com
T
Threat Research - Cisco Blogs
V
V2EX
L
Lohrmann on Cybersecurity
Security Latest
Security Latest
A
Arctic Wolf
Apple Machine Learning Research
Apple Machine Learning Research
H
Hacker News: Front Page
Cisco Talos Blog
Cisco Talos Blog
Webroot Blog
Webroot Blog
T
Tenable Blog
MyScale Blog
MyScale Blog
博客园 - 司徒正美
S
SegmentFault 最新的问题
Y
Y Combinator Blog
腾讯CDC
Hacker News: Ask HN
Hacker News: Ask HN
M
MIT News - Artificial intelligence
G
GRAHAM CLULEY

博客园 - peak

windows 服务器时间同步失败处理方法 利用批处理自动创建schtasks系统任务 抓取网站编码信息及内容 在线调试利器Fiddler AutoResponse Base-64 字符串中的无效字符 Ie7下鼠标滚轮失效 Android 笔记二(取得根目录权限) Android 笔记一 捕获asp.net ValidationSummary 控件消息。 - peak Sql Split 函数 Rss的浏览器之痛 兼容IE,Firefox 图片即时显示 asp.net 中插入flash - peak - 博客园 迷茫 windows service 之访问权限 windows Service 之调试过程 比尔盖兹在某个大学毕业典礼上的演讲中,对毕业生提出十一项极为睿智的人生建议 MSDN上关于泛型的例子 泛型
jquery跨域调用WCF
peak · 2011-12-28 · via 博客园 - peak

  最近在做了一个web和winform通讯的小东西,第一时间想到了通过wcf监听的方式实现。

  方案:winform启动wcf监听程序,前台通过js调用wcf实现通讯。

  1、添加wcf 控制台程序,修改配置文件 binding="webHttpBinding"。

  2、wcf添加接受程序,并返回

  public string GetHello(string s)
  {
    string result = s;
    Console.WriteLine(s);
    return result;
  }

 3、添加webapplication工程,引用jquery.编写调用js脚本

    function callServer1() {
            //ie下需要编码
            var s = escape($("#title").val());
            $.ajax({
                type: "GET",
                url: "http://192.168.23.24/wcf/GetHello",
                data: "s=" + s + "&r=" + Math.random() * 150 + "&callback=?", //调用服务所需要的参数
                contentType: "text/json;charset=utf-8",
                dataType: "json",
                processData: false,
                success: function(msg) {
                    alert(unescape(msg));
                }
            });
        }

基本功能编写完成,调试后发现,web端无法获取返回信息。通过firefox网络可以发现请求信息如下:

 返回信息以json形式返回,并自动添加了 "d":"我的返回字符"。

 这说明信息已经发送到wcf服务端,但是由于产生跨域调用无法返回给请求端。

经过在网上搜索,发现可以通过返回stream的方式实现跨域调用:

wcf改写后代码:

public Stream GetHello(string s, string callBack)
{
//string result = s;
//Console.WriteLine(s);
//return result;
MemoryStream ms = new MemoryStream();
try
{
//接受输入
Console.WriteLine(System.Web.HttpUtility.UrlDecode(s));

//IPHostEntry v = System.Net.Dns.Resolve(System.Net.Dns.GetHostName());
//Console.WriteLine(System.Net.Dns.Resolve(System.Net.Dns.GetHostName()).AddressList.GetValue(0).ToString());//.Current.Request.UserHostAddress;
//string hostName = System.Net.Dns.GetHostName();
//IPHostEntry ipHostEntry = System.Net.Dns.GetHostEntry(hostName);//OperationContext context = OperationContext.Current;
//MessageProperties messageProperties = context.IncomingMessageProperties;
//RemoteEndpointMessageProperty endpointProperty = messageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
//var ipmsg = string.Format("Hello {0}! Your IP address is {1} and your port is {2}", s, endpointProperty.Address, endpointProperty.Port);//获取客户端请求ip
WebOperationContext current = WebOperationContext.Current;
WebHeaderCollection headers = current.IncomingRequest.Headers;
Uri url = new Uri(headers["referer"]);
var host = url.Host;
IPHostEntry cIp = System.Net.Dns.GetHostEntry(host);
var clientIp = cIp.AddressList.GetValue(0).ToString();
Console.WriteLine("客户端请求IP:" + clientIp);
//获取服务本机ip
string hostName = System.Net.Dns.GetHostName();
IPHostEntry ipHostEntry = System.Net.Dns.GetHostEntry(hostName);
var serverIp = ipHostEntry.AddressList.GetValue(0).ToString();
Console.WriteLine("服务本机IP:" + serverIp);

System.Runtime.Serialization.Json.DataContractJsonSerializer formater = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(string));
formater.WriteObject(ms, s);
ms.Position = 0;
string returnStr = "";
using (StreamReader sr = new StreamReader(ms))
{
string objContent = sr.ReadToEnd();
returnStr = callBack + "(" + objContent + ")";
}
ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms);
sw.AutoFlush = true;
sw.Write(returnStr);
ms.Position = 0;
WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain"; //此处一定要是“text/plain”

            }
catch (Exception e)
{ }
return ms;
}

重新调用,成功返回。

参考网文:http://m.cnblogs.com/11042/1444601.html

源码下载