1

私は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>

この問題を解決するのを手伝ってください。

4

1 に答える 1

0

いくつかのダミー コードを追加しました。おそらくほとんどのメソッドも使用されていません。ただし、ダミーの DoubleUp メソッドを使用してコードをテストできます。また、エンドポイント動作を定義しましたが、それが使用されている場合は、エンドポイントに適用する必要があり、重要です。以下の私の例を参照してください。

// 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);
        }
    });
}

于 2013-08-22T10:11:35.633 に答える