繁体   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