wcf服务没有得到html页面的响应

时间:2014-03-07 12:49:58

标签: jquery asp.net ajax wcf

代码

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
    $(document).ready(function () {
        $.ajax({
            url: "http://localhost:3535/WCFService1/Service.svc/rest/hello/Govinda",
            type: "GET",
            success: function (result) {
                alert($(result).find("string").text());
            },
            error: function (error) {
                alert("hi" + error);
            }
        });
    });
</script>

我正在使用wcf service而不是托管在服务器上我只是在本地服务器上测试它。当我在我的.aspx页面中使用上面的代码时,它工作正常。但是当我在.html文件上运行此代码时,它不起作用。这两个文件都在我的项目中。所以,如果有人对这个问题有任何想法,那么请帮助我或建议我在哪里做错了。

4 个答案:

答案 0 :(得分:1)

试试这个!

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
    $(document).ready(function () {
        $.ajax({
            url: "http://localhost:3535/WCFService1/Service.svc/rest/hello/Govinda",
            type: "GET",
            dataType: 'jsonp',
            crossDomain: true,
            success: function (result) {
                alert($(result).find("string").text());
            },
            error: function (error) {
                alert("hi" + error);
            }
        });
    });
</script>

在WCF服务中编辑启用Cors。 http://enable-cors.org/server_wcf.html

答案 1 :(得分:1)

由于同源策略,您的浏览器似乎阻止了请求。尝试使用url的相对路径而不是绝对路径。由于你的html文件在同一个项目中。

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function () {
    $.ajax({
        url: "/WCFService1/Service.svc/rest/hello/Govinda",
        type: "GET",
        success: function (result) {
            alert($(result).find("string").text());
        },
        error: function (error) {
            alert("hi" + error);
        }
    });
});

答案 2 :(得分:1)

您没有从不同机器网址获得任何回复的原因是因为您的网络服务器未配置为使用Cross domain (CORS)

要使其正常运行,您需要在网络服务器上enable CORS

Enabling CORS就像将其添加到网站的web.config

一样简单
<system.webServer>
   <httpProtocol>
     <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
   </httpProtocol>
</system.webServer>

有关CORS工作原理的详细信息,请访问以下链接:

http://encosia.com/using-cors-to-access-asp-net-services-across-domains/

http://blogs.msdn.com/b/carlosfigueira/archive/2012/05/15/implementing-cors-support-in-wcf.aspx?Redirected=true

http://enable-cors.org/server_wcf.html

http://dhvik.blogspot.in/2011/06/supporting-cross-origin-resource.html

答案 3 :(得分:0)

尝试这种方式:

<强> IService.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService" in both code and config file together.
[ServiceContract]
public interface IService
{

    [OperationContract]
    [WebGet (UriTemplate="getData/{value}",ResponseFormat=WebMessageFormat.Json)]
    string GetData(string value);
}

<强> Service.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
public class Service : IService
{
    DataClassesDataContext de = new DataClassesDataContext();
    public string GetData(string value)
    {
        return string.Format("You entered: {0}", value);
    }
}

<强>的Web.config:

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="DatabaseConnectionString" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <services>
      <service name="Service" behaviorConfiguration="ServBehave">
        <!--Endpoint for REST-->
        <endpoint address="rest" binding="webHttpBinding" behaviorConfiguration="restPoxBehavior" contract="IService" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServBehave">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <!--Behavior for the REST endpoint for Help enability-->
        <behavior name="restPoxBehavior">
          <webHttp helpEnabled="true" />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <httpProtocol>
     <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
   </httpProtocol>
    <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>

<强> HTML:

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
        <script>
            $(document).ready(function(){
                $.ajax({
                    url: "http://localhost:4102/Service.svc/rest/getData/Chintan",
                    type: "GET",
                    success: function(result)
                    {
                        alert(result);
                    },
                    error: function(error)
                    {
                        alert("error");
                    }
                });
            });
        </script>
    </head>
    <body>
    </body>
</html>

我正在使用Visual Studio 2013.net framework 4.5