Ajax调用RESTful WCF
这几天在学习RESTful WCF 感觉调用起来比较舒服,就是不能在vs里面直接生成类了。。。 .svc 后面要加上 Factory="System.ServiceModel.Activation.WebServiceHostFactory
先是接口文件: [ServiceContract]
public interface ITestWCF
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json,UriTemplate = "DoWork")]
bool DoWork();
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.Wrapped,UriTemplate = "WebInvokeWithNoArgs",Method = "POST")]
ReturnObj WebInvokeWithNoArgs();
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json,RequestFormat =WebMessageFormat.Json,BodyStyle =WebMessageBodyStyle.WrappedRequest,UriTemplate = "WebInvokeWithArgs",Method = "POST")]
ReturnObj WebInvokeWithArgs(string str);
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json,RequestFormat = WebMessageFormat.Json,UriTemplate = "WebGetWithNoArgs")]
ReturnObj WebGetWithNoArgs();
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json,UriTemplate = "WebGetWithArgs/{str}")]
ReturnObj WebGetWithArgs(string str);
}
然后是实现文件 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class TestWCF : ITestWCF
{
public bool DoWork()
{
return true;
}
public ReturnObj WebGetWithArgs(string str)
{
return new ReturnObj(str);
}
public ReturnObj WebGetWithNoArgs()
{
return new ReturnObj("Get Success!");
}
public ReturnObj WebInvokeWithArgs(string str)
{
return new ReturnObj(str);
}
public ReturnObj WebInvokeWithNoArgs()
{
return new ReturnObj("Invoke Success!");
}
}
解释一下 然后是传送的类: [DataContract]
public class ReturnObj
{
[DataMember(Order = 0)]
public string str;
public ReturnObj(string args)
{
str = args;
}
}
如果想要在json中加入一个字段 就用 DataMember 来标记。如果不加DataMember,json中是看不见这个字段的!而且是否可见跟private public无关。 [DataMember(Order = 0)]
private string str;
[DataMember(Order = 1)]
public int num;
[DataMember(Order = 2)]
public bool ok;
结果就是{“str”:”Invoke Success!”,”num”:1,”ok”:true} 如果是基本类型(比如bool什么的)而且没有选择包装Response的时候就是单纯的值,并没有json格式 然后是配置文件 <system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="TestWCFBehavior"></behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<services>
<service name="TestWCF">
<endpoint address="" behaviorConfiguration="TestWCFBehavior" binding="webHttpBinding" contract="ITestWCF"></endpoint>
</service>
</services>
</system.serviceModel>
配置文件一定要认真的检查有没有漏的,因为配置文件写错了不是服务直接挂了就是访问不到。。。 然后是如何用Ajax调用WCF了。。。 $.ajax({
url: "../TestWCF.svc/WebInvokeWithArgs",type: "POST",contentType: "text/json",asnyc: "false",data: '{"str":"Invoke Test"}',dataType: 'json',success: function (resultObj) {
var resultStr = String(JSON.stringify(resultObj));
alert(resultStr);
},error: function (XMLHttpRequest,textStatus,errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});
GET $.ajax({
url: "TestWCF.svc/WebGetWithArgs/Get Test",type: "Get",asnyc: false,errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});
注意url这三个字母不能大写-_-|| 如果手写ajax的话 <script type="text/javascript"> var xmlHttp; //下面这个函数根据是否为IE浏览器来生成不同ajax对象 function createxmlHttpRequest() { if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } else if (window.XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } } //POST function doPost() { var url = "TestWCF.svc/WebInvokeWithArgs"; var data = '{"str":"Invoke Test"}';//注意为json格式 createxmlHttpRequest(); xmlHttp.open("POST",url,false);//open(方法,地址,同步) xmlHttp.setRequestHeader("Content-Type","text/json"); xmlHttp.onreadystatechange = function () { if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) { alert(xmlHttp.responseText); } else { alert(xmlHttp.status); } } xmlHttp.send(data); return false; } //GET function doGet() { var url = "TestWCF.svc/WebGetWithNoArgs"; createxmlHttpRequest(); xmlHttp.onreadystatechange = function () { if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)) { alert(xmlHttp.responseText); } else { alert(xmlHttp.status); } } xmlHttp.open("GET",false); xmlHttp.send(""); return false; } </script>
注意先设置onreadystatechange 的处理函数再send就行了~ 至于在C#客户端那面就可以用WebHttpRequest和WebHttpResponse来处理 static void Main(string[] args)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:65143/testwcf.svc/WebGetWithNoArgs");
req.Method = "GET";
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
Console.WriteLine(sr.ReadToEnd());
}
POST static void Main(string[] args)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:65143/testwcf.svc/WebInvokeWithArgs");
req.Method = "POST";
req.ContentType = "application/json";
string data = @"{""str"":""From C#""}";
byte[] SendData = Encoding.Default.GetBytes(data);
req.ContentLength = SendData.Length;
req.GetRequestStream().Write(SendData,0,SendData.Length);
req.GetRequestStream().Close();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
Console.WriteLine(sr.ReadToEnd());
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |