【菜鸟学WCF】使用js+ajax调用WCF以及返回数据类型的控制

本文介绍了如何使用JavaScript和AJAX调用WCF服务,强调了在Service1.svc.cs中使用[WebGet]特性标记GET请求,以及在Web.config中设置enableWebScript属性。同时,详细说明了HTML页面中调用WCF服务的URL格式,并给出了返回XML数据格式的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先上代码,再谈问题。


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了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值