简体   繁体   中英

Service not listed when testing WCF

I am trying to test my WCF service for a website I am making. I am using jQuery to call the service ( $.getJSON() ) but I keep getting Connection Refused Error on the website.

So I checked out the website that it makes when I deploy to the computer and my method "GetData()" is not even listed. 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:

服务清单

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:

<?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:

$(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:

[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:

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

After that you should get you data (if everythink is 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. Usualy test client generate invoke methods for SOAP services.

(Wanted to write a comment, but it got quite long...) To create a simple rest service you have to do a few steps:

1) Define service methods and interface:

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. 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:

<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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM