简体   繁体   English

测试WCF时未列出服务

[英]Service not listed when testing WCF

I am trying to test my WCF service for a website I am making. 我正在尝试为正在制作的网站测试WCF服务。 I am using jQuery to call the service ( $.getJSON() ) but I keep getting Connection Refused Error on the website. 我正在使用jQuery调用服务( $.getJSON() ),但是我在网站上不断收到Connection Refused Error。

So I checked out the website that it makes when I deploy to the computer and my method "GetData()" is not even listed. 因此,我签出了部署到计算机时创建的网站,甚至没有列出我的方法“ GetData()”。 It just lists the name of the service itself. 它仅列出服务本身的名称。 I'm fairly new to using WCF in general so have mercy :') In the Test Client that Windows Studio opens my service is not even listed: 我一般来说对使用WCF还是比较陌生,所以请留意:')在Windows Studio打开我的服务的测试客户端中,甚至没有列出:

服务清单

And when I try to add it, it says that the service is successfully added, but nothing shows. 当我尝试添加它时,它表示服务已成功添加,但未显示任何内容。 Earlier today I saw the methods in the list but had to delete the entire project because I messed up. 今天早些时候,我在列表中看到了这些方法,但是由于我搞砸了,所以不得不删除整个项目。

The Web.config looks like this: 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>

Interface: 接口:

[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; }
    }
}

Service: 服务:

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

And lastly, just for good measure, here is the jQuery I use: 最后,出于良好的考虑,这是我使用的jQuery:

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

First of all it will be better if you change the webInvoke attribute from this: 首先,如果您从中更改webInvoke属性,将会更好:

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

To this: 对此:

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

Than run you service and open it in browser by writing url like this: 比运行您的服务并通过编写url这样在浏览器中打开它:

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

After that you should get you data (if everythink is ok) 之后,您应该获取数据(如果一切都OK)

And when I try to add it, it says that the service is successfully added, but nothing shows. 当我尝试添加它时,它表示服务已成功添加,但未显示任何内容。 Earlier today I saw the methods in the list but had to delete the entire project because I messed up. 今天早些时候,我在列表中看到了这些方法,但是由于我搞砸了,所以不得不删除整个项目。

I think it happend because of webHttpBinding (which make your service restful) which you setting up in your web config file. 我认为这是由于在Web配置文件中设置的webHttpBinding(使您的服务稳定)引起的。 Usualy test client generate invoke methods for SOAP services. 通常,测试客户端会为SOAP服务生成调用方法。

(Wanted to write a comment, but it got quite long...) To create a simple rest service you have to do a few steps: (想写评论,但要花很长时间...)要创建一个简单的REST服务,您必须执行一些步骤:

1) Define service methods and interface: 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) Now you have to define the behavior of your service. 2)现在,您必须定义服务的行为。 To do this you have to change the config file in your service project. 为此,您必须在服务项目中更改配置文件。 In this file you have to define the service behavior and another settings that makes your service restful. 在此文件中,您必须定义服务行为以及使您的服务稳定的其他设置。 To do this paste next code inside the serviceModel block: 为此,将下一个代码粘贴到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) Now let's write a method which will invoke our service from javascript: 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