首页 > 解决方案 > WCF 测试客户端,未能调用服务

问题描述

使用 WCF 测试客户端调用以下方法

Service1.svc

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace ShoppingCartService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {
        DigitalXDBEntities _db = new DigitalXDBEntities();

        //Fetches Images from SQL Database
        public string GetImage(object Picture)
        {
            return "data:image/jpg;base64," + Convert.ToBase64String((byte[])Picture);
        }

        //Fetches popular products 
        public List<Product> GetTopProducts()
        {
            var query = (from p in _db.Products
                         orderby p.Price
                         select p).Take(5);

            return query.ToList();
        }

        //Fetches all DVD  using subcategory product id
        public List<Product> GetDvds()
        {

            List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8 };
            var query = (from p in _db.Products
                         where list.Contains(p.SubCategoryID)
                         select p);

            return query.ToList();

        }

        //Fetches all components  using subcategory product id
        public List<Product> GetComponents()
        {
            IEnumerable<int> list = new List<int>() { 25, 31, 29, 30 };
            List<Product> query = (from p in _db.Products
                                   where list.Contains(p.SubCategoryID)
                                   select p).ToList();
            return query;

        }

        //Fetches all Consoles using product id
        public List<Product> GetConsoles()
        {
            IEnumerable<int> list = new List<int>() { 21, 23 };
            List<Product> query = (from p in _db.Products
                                   where list.Contains(p.SubCategoryID)
                                   select p).ToList();
            return query;

        }

        //Fetches all games  using subcategory product id
        public List<Product> GetGames()
        {

            IEnumerable<int> list = new List<int>() { 9, 10, 11, 12, 14, 15 };
            List<Product> query = (from p in _db.Products
                                   where list.Contains(p.SubCategoryID)
                                   select p).ToList();
            return query;

        }

        //Fetches all handbooks  using subcategory product id
        public List<Product> GetHandbooks()
        {
            IEnumerable<int> list = new List<int>() { 27, 28 };
            List<Product> query = (from p in _db.Products
                                   where list.Contains(p.SubCategoryID)
                                   select p).ToList();
            return query;

        }

        //Fetches all pc parts  using subcategory product id
        public List<Product> GetPcParts()
        {
            IEnumerable<int> list = new List<int>() { 26 };
            List<Product> query = (from p in _db.Products
                                   where list.Contains(p.SubCategoryID)
                                   select p).ToList();
            return query;

        }

    }
}

我的服务.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace ShoppingCartService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        List<Product> GetDvds();

        [OperationContract]
        List<Product> GetTopProducts();

        [OperationContract]
        List<Product> GetComponents();

        [OperationContract]
        List<Product> GetGames();

        [OperationContract]
        List<Product> GetHandbooks();

        [OperationContract]
        List<Product> GetPcParts();

    }


    // Use a data contract as illustrated in the sample below to add composite types to service operations.


}

还有我的网络配置

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <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="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <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" />
  </system.webServer>
  <connectionStrings>
  <add name="DigitalXDBEntities" connectionString="metadata=res://*/DigitalX.csdl|res://*/DigitalX.ssdl|res://*/DigitalX.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=DESKTOP-D4D7MNA;initial catalog=DigitalXDB;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework&quot;" providerName="System.Data.EntityClient" /></connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

完整的错误信息

调用服务失败。可能原因:服务离线或无法访问;客户端配置与代理不匹配;现有代理无效。有关更多详细信息,请参阅堆栈跟踪。您可以尝试通过启动新代理、恢复到默认配置或刷新服务来恢复。

接收对http://localhost:56504/Service1.svc的 HTTP 响应时出错。这可能是由于服务端点绑定未使用 HTTP 协议。这也可能是由于服务器中止了 HTTP 请求上下文(可能是由于服务关闭)。有关更多详细信息,请参阅服务器日志。

服务器堆栈跟踪:在 System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
在 System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan 超时)在 System.ServiceModel.Channels.RequestChannel.Request(消息消息,TimeSpan 超时)在 System.ServiceModel.Dispatcher.RequestChannelBinder.Request(消息消息, TimeSpan 超时) 在 System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) 在 System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall , ProxyOperationRuntime 操作) 在 System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage 消息)

在 [0] 处重新抛出异常:在 System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) 在 IService1.GetDvds( ) 在 Service1Client.GetDvds()

内部异常:底层连接已关闭:接收时发生意外错误。在 System.Net.HttpWebRequest.GetResponse() 在 System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan 超时)

内部异常:无法从传输连接读取数据:现有连接被远程主机强行关闭。在 System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size) 在 System.Net.PooledStream.Read(Byte[] buffer, Int32 offset, Int32 size) 在 System.Net.Connection.SyncRead (HttpWebRequest 请求,布尔型 userRetrievedStream,布尔型 probeRead)

内部异常:远程主机在 System.Net.Sockets.NetworkStream.Read(Byte [] 缓冲区,Int32 偏移量,Int32 大小)

我遇到了之前的一篇文章,其中提到将 IEnumerable 列表更改为通用列表,不幸的是这不起作用

编辑:帖子已更新为完整的代码和命名空间

编辑:使用服务提供的默认方法(如下所示)在测试客户端中工作得很好,但是我自己的连接到数据库的方法根本不调用并显示上述错误消息

public string GetData(int value) { return string.Format("You entered: {0}", value); }

标签: c#asp.net-mvcwcf

解决方案


endpoint在您的配置文件中检查 WCF 配置部分,您将看到您也没有任何配置service contract。基本上你完全错过了services下面的部分<system.serviceModel>,我相信这就是问题所在

  <system.serviceModel>
    <behaviors>
      <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="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

根据您编辑的帖子,它应该如下所示

<services> 
<service name="ShoppingCartService.Service1"> 
<endpoint address="" binding="basicHttpBinding" contract="ShoppingCartService.IService1" /> 
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> 
</service> 
</services>

推荐阅读