如何使用ajax从客户端脚本调用WCF服务?

时间:2014-08-11 10:12:53

标签: asp.net ajax wcf

我的服务合约名为IService1,如下

    using System.ServiceModel;
    using System.ServiceModel.Web;

    namespace WcfServiceDemo
    {
        [ServiceContract]
        public interface IService1
        {
            [OperationContract]
            [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
            string GetData(int Value);
        }
    }

这是我的服务实施,

    using System.ServiceModel.Activation;

    namespace WcfServiceDemo
    {
        [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
        public class Service1 : IService1
        {
            public string GetData(int Value)
            {
                return string.Format("You entered: {0}", Value);
            }

        }
    }

我的web.config,

    <?xml version="1.0"?>
    <configuration>

      <system.web>
        <compilation debug="true" targetFramework="4.0" />
      </system.web>
      <system.serviceModel>

        <behaviors>
          <serviceBehaviors>
            <behavior name ="ServiceBehavior">
              <!-- To avoid disclosing metadata information, set the value below to false before deployment -->
              <serviceMetadata httpGetEnabled="true"/>
              <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
              <serviceDebug includeExceptionDetailInFaults="false"/>
            </behavior>
          </serviceBehaviors>
          <endpointBehaviors>
            <behavior name="EndPointBehavior">
              <enableWebScript />
            </behavior>
          </endpointBehaviors>
        </behaviors>

        <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />

        <services>
          <service name ="WcfDemoService" behaviorConfiguration="ServiceBehavior">
            <endpoint address="" binding="webHttpBinding" contract="IService1" behaviorConfiguration="EndPointBehavior" />
          </service>
        </services>

      </system.serviceModel>
     <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
        <!--
            To browse web app root directory during debugging, set the value below to true.
            Set to false before deployment to avoid disclosing web app folder information.
          -->
        <directoryBrowse enabled="true"/>
      </system.webServer>

    </configuration>

使用WCF服务的脚本,

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Client.aspx.cs"       Inherits="WcfServiceDemo.Client" %>

    <!DOCTYPE html>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            Enter a number:<input type="text" id="txtNum"/>
            <input type="button" onclick="AlertEnteredNum();"/>
        </div>
        </form>
        <script type="text/javascript" src="Script/jquery-1.3.2.min.js"></script>
        <script type="text/javascript">
            function AlertEnteredNum() {
                var Value = $('#txtNum').val();
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: 'Service1.svc/GetData',
                    data: '{"Value": "' + Value + '"}',
                    dataType: "json",
                    processData: false,
                    success: function (data) {
                        alert("Success: " + data.d);
                    },
                    error: function (result) {
                        alert("error: " + result);
                    }
                });
            }
        </script>
    </body>
    </html>

始终执行错误回调。有人能告诉我这里缺少什么吗?

我想我需要在IIS上托管,因为我在配置中设置兼容模式。但, 当我在IIS上托管此服务时,我收到解析器错误,因为&#34;无法识别的属性&#39; targetFramework&#39;。请注意,属性名称区分大小写。&#34;

并且,如果我删除了这个&#34; targetFramework = 4&#34;属性,我得到一个例外&#34;无法加载文件或程序集&#39; WcfServiceDemo&#39;或其中一个依赖项。此程序集由比当前加载的运行时更新的运行时构建,无法加载。&#34;

2 个答案:

答案 0 :(得分:1)

针对TargetFramework问题。 您应检查您的应用程序池是.net4.0而不是.net2.0

javascript似乎是正确的

答案 1 :(得分:1)

终于犯了我的错误&amp;它的解决方案。

只需将config中的service元素更改为:

<services>
  <service name ="WcfServiceDemo.Service1" behaviorConfiguration="ServiceBehavior">
    <endpoint address="" binding="webHttpBinding" contract="WcfServiceDemo.IService1" behaviorConfiguration="EndPointBehavior" />
  </service>
</services>

其中name =&#34; WcfServiceDemo.Service1&#34;格式为&#34; namespace.ServiceImplementationName&#34; &安培;合同=&#34; WcfServiceDemo.IService1&#34;格式为&#34; namespace.ServiceContractName&#34;