如何通过ajax getJSON使用WCF服务方法?

时间:2014-08-14 19:58:33

标签: c# ajax wcf getjson

这是默认情况下在Visual Studio 2013中创建的代码。 在项目属性中,我将其设置为使用本地IIS。 WCF测试客户端成功测试它。 在同一个项目中,我添加了html页面,试图通过getJSON获取方法,但是我收到了来自.fail部分的“Not Found”错误 我应该修改什么才能通过getJSON使用它? 注意:我理解方法GetTime在浏览器中也是“不可见的”(“400 Bad Request”),我需要配置端点,我查了一下,但我的尝试都没有成功..

IService1.cs

using System.Runtime.Serialization;
using System.ServiceModel;
namespace WcfService1
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string GetTime();
    }
}

Service1.svc.cs

using System;
namespace WcfService1
{
    public class Service1 : IService1
    {
        public string GetTime()
        {
            return DateTime.Now.ToShortTimeString();
        }
    }
}

的web.config

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

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

HTMLPage1.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
    <body>
        <div>
            <span id="jspan"></span>
        </div>
</html>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        var prom = $.getJSON("http://localhost/Service1.svc/GetTime");

        prom.done(function (data) {
            $("#jspan").text("data: " + data.d);
        })
            .fail(function (data) {
                $("#jspan").text("error: " + data.statusText);
            });

    });
</script>

1 个答案:

答案 0 :(得分:0)

为了通过ajax访问web服务方法,我需要能够通过http访问它(在浏览器中查看)。 因此,第一步是为此配置Web服务行为。我在这里回答: How to access WCF service methods from browser? 然后我们“像往常一样”调用我们的ajax方法。代码见下文。

IService1.cs

using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
namespace WcfService1
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet]
        string GetTime();
    }
}

的web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>

      **<!--added behavior-->
      <endpointBehaviors>
        <behavior name="WcfService1.Service1AspNetAjaxBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>**

    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

    **<!--added service behaviour configuration-->
    <services>
      <service name="WcfService1.Service1">
        <endpoint address="" behaviorConfiguration="WcfService1.Service1AspNetAjaxBehavior"
          binding="webHttpBinding" contract="WcfService1.IService1" />
      </service>
    </services>**

  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

带有java脚本的HtmlPage1.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
    <body>
        <div>
            <span id="jspan"></span>
        </div>
    </body>
</html>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        var prom = $.getJSON("http://localhost/WcfService1/Service1.svc/GetTime");

        prom.done(function (data) {
            $("#jspan").text("data: " + data.d);
        })
            .fail(function (data) {
                $("#jspan").text("error: " + data.statusText);
            });

    });
</script>

结果应如下所示:

Client app and method in the browser screen shot