【菜鳥學WCF】使用js+ajax呼叫WCF以及返回資料型別的控制
阿新 • • 發佈:2019-02-18
先上程式碼,再談問題。
Service1.svc.cs程式碼:
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Web; using System.Text; namespace WebApplication1 { [ServiceContract(Namespace = "GLM")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class Service1 { [OperationContract] [WebGet]//必須有這個特性,與Html頁面中的ajax呼叫"GET"對應 public string DoWork() { return "DoWork called"; } } }
Service1.svc程式碼:
<%@ ServiceHost Language="C#" Debug="true" Service="WebApplication1.Service1" CodeBehind="Service1.svc.cs" %>
HTMLPage1.htm程式碼:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script type="text/javascript"> function test() { var xmlhttp = CreateXmlHttpReq(); if (xmlhttp == null) return; var url = "Service1.svc/myEndpoint/DoWork"; xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && (xmlhttp.status == 200 || xmlhttp.status == 0)) { alert(xmlhttp.responseText); } } xmlhttp.open("GET", url, true); xmlhttp.send(null); } //建立XmlHttpRequest物件 function CreateXmlHttpReq() { var xmlhttp = null; try { xmlhttp = new XMLHttpRequest(); } catch (e) { try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Oops!Your Browser does not support Ajax"); } } } return xmlhttp; } </script> </head> <body> <input id="button1" type="button" value="click me" onclick="return test();" /> </body> </html>
Web.config標記如下:
<?xml version="1.0" encoding="utf-8"?> <!-- 有關如何配置 ASP.NET 應用程式的詳細訊息,請訪問 http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.serviceModel> <behaviors> <endpointBehaviors> <behavior name="WebApplication1.Service1AspNetAjaxBehavior"> <webHttp/> </behavior> </endpointBehaviors> </behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> <services> <service name="WebApplication1.Service1"> <endpoint address="myEndpoint" behaviorConfiguration="WebApplication1.Service1AspNetAjaxBehavior" binding="webHttpBinding" contract="WebApplication1.Service1" /> </service> </services> </system.serviceModel> </configuration>
下面說說注意事項:
1、在Service1的DoWork定義上要用[WebGet]特性標記(預設是[WebInvoke]),因為在html頁面中,我們通過xmlhttp.Open("GET".....)這樣GET呼叫的。如果xmlhttp使用POST方法呼叫WCF服務,則DoWork需要用[WebInvoke]來標記;
2、在配置檔案Web.config中,需要把endpointbehaviour節點下的behavior中的enableWebScript改成webHttp;
<behaviors>
<endpointBehaviors>
<behavior name="WebApplication1.Service1AspNetAjaxBehavior">
<!--請看這裡,原來是enableWebScript-->
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
3、在html頁面中,ajax呼叫的url為Service1.svc/myEndpoint/DoWork,其中myEndpoint為endpoint的地址,該地址在配置檔案中賦值:
<service name="WebApplication1.Service1">
<!--請看這裡的address屬性-->
<endpoint address="myEndpoint" behaviorConfiguration="WebApplication1.Service1AspNetAjaxBehavior"
binding="webHttpBinding" contract="WebApplication1.Service1" />
</service>
如果address=“”(賦值為空字串),則url應該寫成Service1.svc/DoWork。
如何控制請求和相應的資料格式呢,很簡單,例如:
[OperationContract]
[WebGet(ResponseFormat=WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.Wrapped)]
public string DoWork()
{
return "DoWork called";
}
這樣,呼叫DoWork就會返回json格式的資料了:
如果想返回xml格式的資料,只要更改ResponseFormat就OK了