簡體   English   中英

測試WCF時未列出服務

[英]Service not listed when testing WCF

我正在嘗試為正在制作的網站測試WCF服務。 我正在使用jQuery調用服務( $.getJSON() ),但是我在網站上不斷收到Connection Refused Error。

因此,我簽出了部署到計算機時創建的網站,甚至沒有列出我的方法“ GetData()”。 它僅列出服務本身的名稱。 我一般來說對使用WCF還是比較陌生,所以請留意:')在Windows Studio打開我的服務的測試客戶端中,甚至沒有列出:

服務清單

當我嘗試添加它時,它表示服務已成功添加,但未顯示任何內容。 今天早些時候,我在列表中看到了這些方法,但是由於我搞砸了,所以不得不刪除整個項目。

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 name="ServiceBehavior">
          <!-- 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="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="EndpBehavior">
          <webHttp/>
        </behavior>
        <behavior name="enableScriptBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="PUendeligWebService.ExampleService">
        <endpoint address="" binding="webHttpBinding" 
                  contract="PUendeligWebService.ExampleServiceInterface" behaviorConfiguration="EndpBehavior"/>
      </service>
    </services>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </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"/>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*"/>
      </customHeaders>
    </httpProtocol>
  </system.webServer>

</configuration>

接口:

[ServiceContract]
public interface ExampleServiceInterface
{
    [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
    String GetData();

    [OperationContract]
    CompositeType GetDataUsingDataContract(CompositeType composite);
}


[DataContract]
public class CompositeType
{
    bool boolValue = true;
    string stringValue = "Hello ";

    [DataMember]
    public bool BoolValue
    {
        get { return boolValue; }
        set { boolValue = value; }
    }

    [DataMember]
    public string StringValue
    {
        get { return stringValue; }
        set { stringValue = value; }
    }
}

服務:

public class ExampleService : ExampleServiceInterface
{
    public String GetData()
    {
        Random ran = new Random();
        TestClass[] tc = new TestClass[5];
        TestClass tc1 = new TestClass();
        tc1.TheText = "First Text " + ran.Next();
        tc1.TheOtherText = "First Other Text " + ran.Next();
        TestClass tc2 = new TestClass();
        tc2.TheText = "Second Text " + ran.Next();
        tc2.TheOtherText = "Second Other Text " + ran.Next();
        TestClass tc3 = new TestClass();
        tc3.TheText = "Third Text " + ran.Next();
        tc3.TheOtherText = "Third Other Text " + ran.Next();
        TestClass tc4 = new TestClass();
        tc4.TheText = "Fourth Text " + ran.Next();
        tc4.TheOtherText = "Fourth Other Text " + ran.Next();
        TestClass tc5 = new TestClass();
        tc5.TheText = "Fifth Text " + ran.Next();
        tc5.TheOtherText = "Fifth Other Text " + ran.Next();

        tc[0] = tc1;
        tc[1] = tc2;
        tc[2] = tc3;
        tc[3] = tc4;
        tc[4] = tc5;

        return JsonConvert.SerializeObject(tc);
    }

    public CompositeType GetDataUsingDataContract(CompositeType composite)
    {
        if (composite == null)
        {
            throw new ArgumentNullException("composite");
        }
        if (composite.BoolValue)
        {
            composite.StringValue += "Suffix";
        }
        return composite;
    }
}

最后,出於良好的考慮,這是我使用的jQuery:

$(function() {
    $("input:button").click(function() {
        $.getJSON("http://localhost:52535/ExampleService.svc/GetData?callback=?", function(data) {
            alert(data);
        });
    });
});

首先,如果您從中更改webInvoke屬性,將會更好:

[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)]
String GetData();

對此:

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json, UriTemplate="/getData")]
String GetData();

比運行您的服務並通過編寫url這樣在瀏覽器中打開它:

http://host_name:port_number/service_name.svc/getData

之后,您應該獲取數據(如果一切都OK)

當我嘗試添加它時,它表示服務已成功添加,但未顯示任何內容。 今天早些時候,我在列表中看到了這些方法,但是由於我搞砸了,所以不得不刪除整個項目。

我認為這是由於在Web配置文件中設置的webHttpBinding(使您的服務穩定)引起的。 通常,測試客戶端會為SOAP服務生成調用方法。

(想寫評論,但要花很長時間...)要創建一個簡單的REST服務,您必須執行一些步驟:

1)定義服務方法和接口:

namespace CoreAuroraService.Services
{
    [DataContract]
    public class Patient 
    {
        [DataMember]
        public String LastName{get;set;}

        [DataMember]
        public string FirstName{get;set;}
    }

    [ServiceContract]
    public interface IPatientService
    {
        [OperationContract]
        [WebGet(UriTemplate = "/GetAllPatients", ResponseFormat = WebMessageFormat.Json)]
        List<Patient> GetAllPatients();

        [OperationContract]
        [WebInvoke(UriTemplate = "/Create", Method = "POST", ResponseFormat = WebMessageFormat.Json)]
        bool CreatePatient();


        [OperationContract]
        [WebInvoke(UriTemplate = "/Update", Method = "PUT", ResponseFormat = WebMessageFormat.Json)]
        bool UpdatePatient(Guid patientGuid);


        [OperationContract]
        [WebInvoke(UriTemplate = "/Delete", Method = "DELETE", ResponseFormat = WebMessageFormat.Json)]
        bool DeletePatient(Guid patientGuid);
    }

    public class PatientService : IPatientService
    {
        public List<Patient> GetAllPatients()
        {
            var patient = new Patient() { FirstName = "Jeem", LastName = "Street" };
            var patients = new List<Patient> { patient };
            return patients;
        }

        public bool CreatePatient()
        {
            // TODO: Implement the logic of the method here
            return true;
        }

        public bool UpdatePatient(Guid patientGuid)
        {
            // TODO: Implement the logic of the method here
            return true;
        }

        public bool DeletePatient(Guid patientGuid)
        {
            // TODO: Implement the logic of the method here
            return true;
        }
    }
}

2)現在,您必須定義服務的行為。 為此,您必須在服務項目中更改配置文件。 在此文件中,您必須定義服務行為以及使您的服務穩定的其他設置。 為此,將下一個代碼粘貼到serviceModel塊中:

<services>
  <service name="CoreAuroraService.Services.PatientService">
    <endpoint address="" behaviorConfiguration="rest" binding="webHttpBinding" bindingConfiguration="maxStream" contract="CoreAuroraService.Services.IPatientService">
      <identity>
        <dns value="localhost"/>
      </identity>
    </endpoint>
    <host>
      <baseAddresses>
        <add baseAddress="https://localhost/Services/PatientService.svc"/>
      </baseAddresses>
    </host>
  </service>
</services>

<behaviors>
  <endpointBehaviors>
    <behavior name="rest">
      <webHttp helpEnabled="true"/>
    </behavior>
  </endpointBehaviors>
  <serviceBehaviors>
    <behavior>
      <!-- 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="true"/>
    </behavior>
  </serviceBehaviors>
</behaviors>

3)現在,讓我們編寫一個方法,該方法將從javascript調用我們的服務:

<script>
    function GetP() {
        // Now I need to send cross domain request to the service because my services hosted in another project
        // Tested in IE 11
        var url = "http://localhost:29358/Services/PatientService.svc/GetAllPatients";
        $.ajax({
            type: 'GET',
            dataType: "text",
            url: url,
            success: function (responseData, textStatus, jqXHR) {
                console.log("in");
                var data = JSON.parse(responseData);
                console.log(data);
            },
            error: function (responseData, textStatus, errorThrown) {
                alert('POST failed.');
            }
        });
    }
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM