jquery跨域调用WCF
最近在做了一个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;
}
重新调用,成功返回。