使用JQuery调用WCF服务时WCF服务调用失败

时间:2013-08-22 06:01:45

标签: asp.net wcf jquery

我正在使用asp.net。我在C#中创建了一个WCF服务并托管在IIS服务器上。我在我的asp.net Web应用程序中使用JQuery调用此服务。当我使用JQuery调用服务时,它将进入错误功能,并在警报中有空消息。

调用服务表单.aspx页面。

<script src="Script/jquery-1.10.2.min.js" type="text/javascript"></script>

<script type="text/javascript" language="javascript">
function callService()
{
    var value = 10;
    $.ajax({
        type: "POST",
        url: "http://localhost/IISWCF/Service1.svc/getdata",
        contentType: "application/json; charset=utf-8",
        data: '{"value": "' + value + '"}',
        dataType: "json",
        processdata: true, //True or False
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("error: " + errorThrown);
        },
        success: function(msg) {
            alert(msg.d);
        }
    });
}
</script>

<script type="text/javascript" language="javascript">
$(document).ready(function(){
    callService();
})
</script>

Service1.svc文件

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

IService1.cs文件

namespace WcfService1
{
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
        string GetData(int value);
    }
}

WCF Web.config文件

    <system.serviceModel>
  <behaviors>
    <serviceBehaviors>
      <behavior name="WcfService1.Service1Behavior">
        <serviceMetadata httpGetEnabled="true"/>
        <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
    </serviceBehaviors>
    <endpointBehaviors>
      <behavior name="EndpBehavior">
        <webHttp/>
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <services>
    <service name="WcfService1.Service1" behaviorConfiguration="WcfService1.Service1Behavior">
      <endpoint behaviorConfiguration="EndpBehavior" address="" binding="webHttpBinding" contract="WcfService1.IService1">
        <identity>
          <dns value="localhost"/>
        </identity>
      </endpoint>
      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
    </service>
  </services>
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true"   />
</system.serviceModel>

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

我添加了一些虚拟代码,可能很少有方法也没用过。但您可以使用虚拟DoubleUp方法测试代码。此外,您已定义endpointbehavior,但是它已被使用,它应该应用于端点及其重要性。参考下面的例子。

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

    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate = "/DoubleUp/{val}")]
    int DoubleUp(string val);

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

    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    string ConcatenateString(string stringArray);
}  


public class CalculationService : ICalculatorService
{

    public int DoubleUp(string val)
    {
        return 2 * Convert.ToInt32(val);
    }

    public int AddValues(string value, string value1)
    {
        return Convert.ToInt32(value) + Convert.ToInt32(value1);
    }

    public string ConcatenateString(string stringArray)
    {
        string returnString = string.Empty;
        returnString += stringArray;           

        return returnString;
    }
}

<system.serviceModel>
<bindings>
  <webHttpBinding>
    <binding name="JSONBinding"></binding>
  </webHttpBinding>
  <basicHttpBinding>
    <binding name="basicHTTP">
      <security mode="None">

      </security>
    </binding>
  </basicHttpBinding>
</bindings>
<behaviors>
  <serviceBehaviors>
    <behavior name="basicBehavior">
      <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="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="JSON">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<services>
<service name="RestWCFService.CalculationService" behaviorConfiguration="basicBehavior">
    <endpoint address="basic" binding="basicHttpBinding" contract="RestWCFService.ICalculatorService" bindingName ="basicHTTP"></endpoint>
    <endpoint behaviorConfiguration="JSON" binding="webHttpBinding" bindingConfiguration="JSONBinding" contract="RestWCFService.ICalculatorService" name="JSONService"></endpoint>
  </service>      
</services>

<protocolMapping>
    <add binding="basicHttpBinding" scheme="http"/>
    <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>    
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>



 /* This is the code for accessing the service via REST call
        WebClient client = new WebClient();
        string s = client.DownloadString("http://localhost/RestWCFService/CalculationService.svc/DoubleUp/3");
        Console.WriteLine("Response returned is:" + s);
        */

        /*This is the section to access service via Proxy */

        ChannelFactory<RestWCFService.ICalculatorService> client = new ChannelFactory<RestWCFService.ICalculatorService>();

        client.Endpoint.Address = new EndpointAddress("http://localhost/RestWCFService/CalculationService.svc/basic");
        client.Endpoint.Binding = new BasicHttpBinding();
        RestWCFService.ICalculatorService service = client.CreateChannel();

        int val = service.DoubleUp("2");
        ((IClientChannel)service).Close();
        client.Close();

        Console.WriteLine("Values returned is:" + val.ToString());

        /*Programmatic access ends here */

        Console.ReadLine();

您的服务运作正常。做了一些改变。

[ServiceContract]
public interface IService1
{

    [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate="/GetData?value={value}")]
    string GetData(int value);
}

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

 <system.serviceModel>    
  <behaviors>
    <serviceBehaviors>
      <behavior name="WcfService1.Service1Behavior">
        <serviceMetadata httpGetEnabled="true"/>
        <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
    </serviceBehaviors>
    <endpointBehaviors>
      <behavior name="EndpBehavior">
        <webHttp/>
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <services>
    <service name="WcfService1.Service1" behaviorConfiguration="WcfService1.Service1Behavior">
      <endpoint behaviorConfiguration="EndpBehavior" address="" binding="webHttpBinding" contract="WcfService1.IService1">
        <identity>
          <dns value="localhost"/>
        </identity>
      </endpoint>
      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
    </service>
  </services>
<protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>    
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"   />
</system.serviceModel>

在浏览器上访问该服务,您将获得结果。

http://localhost/IISWCF/Service1.svc/GetData?value=1

如果您的服务运行正常,请尝试使用此JS,因为您的JS对此服务请求不正确。

<script type="text/javascript" language="javascript">
function callService() {
    var value = 10;
    $.ajax({
        type: "GET",
        url: "http://localhost/IISWCF/Service1.svc/GetData?value=1",
        contentType: "application/json; charset=utf-8",
        data: '{"value": "' + value + '"}',
        dataType: "text",
        processdata: false, //True or False
        statusCode: {
            404: function () {
                alert("page not found");
            },
            200: function () {
                alert('HTTP HIT WAS Good.');
            },
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("error: " + errorThrown);
        },
        success: function (msg) {
            alert(msg);
        }
    });
}