C# 测试WCF时未列出服务

C# 测试WCF时未列出服务,c#,jquery,web-services,wcf,localhost,C#,Jquery,Web Services,Wcf,Localhost,我试图测试我的WCF服务的网站,我正在做。我正在使用jQuery调用服务($.getJSON()),但我一直在网站上收到连接被拒绝错误 因此,我查看了它在部署到计算机时创建的网站,我的方法“GetData()”甚至没有列出。它只列出服务本身的名称。一般来说,我对使用WCF还比较陌生,所以发发慈悲吧:')在Windows Studio打开我的服务的测试客户端中,甚至没有列出: 当我尝试添加它时,它说服务已成功添加,但没有显示任何内容。今天早些时候,我看到了列表中的方法,但由于我搞砸了,不得不删除

我试图测试我的WCF服务的网站,我正在做。我正在使用jQuery调用服务(
$.getJSON()
),但我一直在网站上收到连接被拒绝错误

因此,我查看了它在部署到计算机时创建的网站,我的方法“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>
http://host_name:port_number/service_name.svc/getData
服务:

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打开它:

<?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>
http://host_name:port_number/service_name.svc/getData
之后,您应该获得数据(如果一切正常)

当我尝试添加它时,它表示服务成功 补充,但没有显示。今天早些时候,我看到了列表中的方法 但我不得不删除整个项目,因为我搞砸了

我认为这是因为您在web配置文件中设置了webHttpBinding(使您的服务restful)。通常,测试客户端会为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;
        }
    }
}
namespace corearoraservice.Services
{
[数据合同]
公立病人
{
[数据成员]
公共字符串LastName{get;set;}
[数据成员]
公共字符串名{get;set;}
}
[服务合同]
公共接口iPartientService
{
[经营合同]
[WebGet(UriTemplate=“/GetAllPatients”,ResponseFormat=WebMessageFormat.Json)]
列出GetAllPatients();
[经营合同]
[WebInvoke(UriTemplate=“/Create”,Method=“POST”,ResponseFormat=WebMessageFormat.Json)]
bool-CreatePatient();
[经营合同]
[WebInvoke(UriTemplate=“/Update”,Method=“PUT”,ResponseFormat=WebMessageFormat.Json)]
bool UpdatePatient(Guid patientGuid);
[经营合同]
[WebInvoke(UriTemplate=“/Delete”,Method=“Delete”,ResponseFormat=WebMessageFormat.Json)]
bool DeletePatient(Guid patientGuid);
}
公共类患者服务:IPatientService
{
公共列表GetAllPatients()
{
var patient=new patient(){FirstName=“Jeem”,LastName=“Street”};
var patients=新列表{patient};
返回病人;
}
公立医院
{
//TODO:在此处实现方法的逻辑
返回true;
}
public bool UpdatePatient(Guid patientGuid)
{
//TODO:在此处实现方法的逻辑
返回true;
}
公共bool DeletePatient(Guid patientGuid)
{
//TODO:在此处实现方法的逻辑
返回true;
}
}
}
2) 现在,您必须定义服务的行为。为此,您必须更改服务项目中的配置文件。在这个文件中,您必须定义服务行为和使您的服务restful的其他设置。要执行此操作,请在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>

函数GetP(){
//现在我需要向服务发送跨域请求,因为我的服务托管在另一个项目中
//在IE11中测试
变量url=”http://localhost:29358/Services/PatientService.svc/GetAllPatients";
$.ajax({
键入:“GET”,
数据类型:“文本”,
url:url,
成功:函数(responseData、textStatus、jqXHR){
控制台。登录(“登录”);
var data=JSON.parse(responseData);
控制台日志(数据);
},
错误:函数(响应数据、文本状态、错误抛出){
警报(“POST失败”);
}
});
}

不是那个特定的端口,不是。我正在使用部署到自己端口的Netbeans创建网站。请尝试在发行版中构建解决方案,而不是调试,然后再试一次。我在尝试WCF测试客户端时遇到了类似的问题,当我更改生成模式时,它会有所帮助,因为它显然需要发布版本中的.dll文件。@urbz它不起作用。它得到了完全相同的行为:/既然你说你必须删除整个项目,那到底是什么意思?你重建了你的VS项目吗?如果是这样,请仔细检查端点配置是否与类型和命名空间完全匹配。您的web.config显示PUendeligWebService。这是否仍然准确?@S.Brentson这意味着我必须删除整个项目,然后使用Visual Studio向导创建一个新项目:)是的,名称是正确的。当我使用访问该方法时,我会看到一个页面,上面写着“不允许该方法”。我如何更改配置以便可以返回到SOAP服务而不是REST?该网站也给了我一个405错误时使用的方法。嗯,我得到了一些进展。我进入我的WebInvoke属性并添加了“Method=“*”,现在它可以工作了。现在我只需要弄清楚如何解析我收到的JSON字符串。为此,您可以使用JSON.parse()方法,就像这里解释的那样。我还想知道您需要REST还是S类型的服务