Тестовый клиент WCF, не удалось вызвать службу - PullRequest
0 голосов
/ 17 мая 2018

Использование тестового клиента 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;

        }

    }
}

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


}

И мой webconfig

<?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 на http://localhost:56504/Service1.svc. Это может быть связано с тем, что привязка конечной точки службы не использует протокол 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 timeout) в System.ServiceModel.Dispatcher.RequestChannelBinder.Request (Message сообщение, TimeSpan timeout) в System.ServiceModel.Channels.ServiceChannel.Call (Строковое действие, Boolean oneway, операция ProxyOperationRuntime, Object [] ins, Object [] outs, TimeSpan timeout) в System.ServiceModel.Channels.ServiceChannelProxy.InvokeService (IMethodCallMessage methodCall, операция ProxyOperationRuntime) в System.ServiceModel.Channels.ServiceChannelProxy.Invoke (Шеззаде сообщение)

Исключение переброшено в [0]: в System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage (Шеззаде reqMsg, IMessage retMsg) в System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke (MessageData & msgData, тип Int32) в IService1.GetDvds () в Service1Client.GetDvds ()

Внутреннее исключение: базовое соединение было закрыто: неожиданно Произошла ошибка при получении. в System.Net.HttpWebRequest.GetResponse () в System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply (TimeSpan Тайм-аут)

Внутреннее исключение: невозможно прочитать данные из транспортного соединения: An существующее соединение было принудительно закрыто удаленным хостом. в 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) в System.Net.Sockets.NetworkStream.Read (буфер Byte [], смещение Int32, Размер Int32)

Я сталкивался с предыдущим постом, в котором упоминалось изменение списка IEnumerable в общий список, к сожалению, он не работал

РЕДАКТИРОВАТЬ: Сообщение было обновлено с полным кодом и пространством имен

РЕДАКТИРОВАТЬ: Использование метода по умолчанию, предоставляемого службой (показано ниже), прекрасно работает в тестовом клиенте, однако мои собственные методы, которые подключаются к БД, вообще не запускаются и показывают указанное выше сообщение об ошибке

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

1 Ответ

0 голосов
/ 17 мая 2018

В вашем конфигурационном файле проверьте деталь для конфигурации WCF, и вы увидите, что у вас нет конфигурации для endpoint и 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...