【问题标题】:WCF Test Client, failed to invoke the serviceWCF 测试客户端,未能调用服务
【发布时间】:2018-05-17 08:50:31
【问题描述】:

使用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;

        }

    }
}

我的 Iservice.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 请求, 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.ServiceChannel.Call(字符串动作, Boolean oneway, ProxyOperationRuntime 操作, Object[] ins, Object[] 出局,TimeSpan 超时)在 System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall,ProxyOperationRuntime 操作)在 System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage 留言)

在 [0] 处重新抛出异常:在 System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg,IMessage retMsg)在 System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(消息数据& msgData,Int32 类型)在 IService1.GetDvds() 在 Service1Client.GetDvds()

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

内部异常:无法从传输连接读取数据:一个 现有连接被远程主机强行关闭。在 System.Net.Sockets.NetworkStream.Read(Byte[] 缓冲区,Int32 偏移量, Int32 大小)在 System.Net.PooledStream.Read(Byte[] 缓冲区,Int32 偏移量,Int32 大小)在 System.Net.Connection.SyncRead(HttpWebRequest 请求,布尔值 userRetrievedStream, Boolean probeRead)

内部异常:现有连接被强制关闭 System.Net.Sockets.Socket.Receive(Byte[] 缓冲区的远程主机, Int32 偏移量,Int32 大小,SocketFlags socketFlags) at System.Net.Sockets.NetworkStream.Read(Byte[] 缓冲区,Int32 偏移量, int32 大小)

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

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

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

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

【问题讨论】:

  • 在我的帖子中添加了更多详细信息

标签: c# asp.net-mvc wcf


【解决方案1】:

在您的配置文件中检查 WCF 配置部分,您会发现您也没有任何 endpointservice contract 配置。基本上你完全错过了&lt;system.serviceModel&gt; 下的services 部分,我相信这就是这里的问题

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

【讨论】:

  • 我已经在 但它说'name'属性无效-值 'ShoppingCartService.IService1' 根据其数据类型 serviceNameTy[e' 无效 - 枚举约束失败...
  • 也许再多一点指导?
  • @invrt 当然可以,但我需要更多信息...发布您的 wcf 服务的代码...以及带有命名空间的完整代码
  • 我的原始帖子已更新为完整代码@rahul
  • 不幸的是您的编辑没有解决问题,仍然收到上述错误消息:(@rahul
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-27
  • 1970-01-01
  • 2010-10-10
  • 2013-07-05
  • 1970-01-01
  • 2011-07-10
相关资源
最近更新 更多