Web (ASP.Net) Wcf: не найден Ошибка подключения с настольного клиента - PullRequest
0 голосов
/ 29 марта 2019

Я настраиваю поддомен ASP.Net WebForms с WCF, размещенным на учетной записи общего хостинга. WCF является основной целью сайта на данный момент. У меня проблемы с установкой ссылки с моего рабочего стола, что приводит к вечному

Невозможно подключиться к удаленному серверу

Я пытаюсь как из Add Service Reference, так и из C #. Я хочу код C # в конце на клиенте.

Я продолжаю играть с номерами портов и различными типами привязок, но ничего не работает.

Web.config

<?xml version="1.0"?>
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.6.2"/>
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>
    <system.serviceModel>
        <services>
            <service name="MyCloud.Communication.CloudService" behaviorConfiguration="BehaviorMyCloudService">
                <endpoint address=""
                                    binding="wsHttpBinding"
                                    bindingConfiguration="EndpointBindingMyCloudService"
                                    contract="MyCloud.Communication.ICloudService"
                                    behaviorConfiguration="web"
                                    >
                </endpoint>
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
                <host>
                    <baseAddresses>
                        <add baseAddress="http://localhost/MyCloudService/"/>
                    </baseAddresses>
                </host>
            </service>
        </services>
        <behaviors>
            <serviceBehaviors>
                <behavior name="BehaviorMyCloudService">
                    <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="true" />
                    <dataContractSerializer maxItemsInObjectGraph="2147483647" />
                    <useRequestHeadersForMetadataAddress>
                        <defaultPorts>
                            <add scheme="http" port="8080" />
                        </defaultPorts>
                    </useRequestHeadersForMetadataAddress>
                </behavior>
                <behavior name="">
                    <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="false" />
                </behavior>
            </serviceBehaviors>
            <endpointBehaviors>
                <behavior name="web">
                    <webHttp />
                </behavior>
            </endpointBehaviors>
        </behaviors>
        <bindings>
            <wsHttpBinding>
                <binding
                    name="EndpointBindingMyCloudService"
                    allowCookies="false"
                    closeTimeout="00:01:00"
                    openTimeout="00:01:00"
                    receiveTimeout="00:10:00"
                    sendTimeout="00:01:00"
                    maxBufferPoolSize="524288"
                    maxReceivedMessageSize="2147483647"
                    messageEncoding="Text"
                    textEncoding="utf-8"
                    transactionFlow="false"
                    useDefaultWebProxy="true"
                    >
                    <security mode="None">
                    </security>
                </binding>
            </wsHttpBinding>
        </bindings>
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true">
            <baseAddressPrefixFilters>
                <add prefix="http://localhost:8080"/>
            </baseAddressPrefixFilters>
        </serviceHostingEnvironment>
    </system.serviceModel>
</configuration>

CloudService.svc (код C #) :

using System;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Web;

namespace MyCloud.Communication
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class CloudService : ICloudService, IErrorHandler
    {
        public UInt16 GetServiceId()
        {
            return MyCloudLibrary.Constants.My_Id_CloudService;
        }
    }
}

ICloudService.cs

using System;
using System.IO;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace MyCloud.Communication
{
    [ServiceContract(SessionMode = SessionMode.Allowed/*, CallbackContract = typeof(ICallbackCloudService)*/)]
    public interface ICloudService
    {
        [OperationContract(IsOneWay = false)]
        [FaultContractAttribute(typeof(CloudServiceFault))]
        UInt16 GetServiceId();
    }
}

Код C # на стороне клиента :

WSHttpBinding binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.None;
EndpointAddress endpointAddress = new EndpointAddress("http://Mycloud.asdfmydomain.com/MyCloudService");
var pipeFactory = new ChannelFactory<ICloudService>(binding, endpointAddress);
Program.HostIpcCloudService = pipeFactory.CreateChannel();
Program.HostIpcCloudService.Connect();
CommCloudService.IsPipeCloudService = true;
UInt16 serviceId = Program.HostIpcCloudService.GetServiceId();

Ошибка C # на стороне клиента :

OuterException:

"Конечная точка не слушала http://mycloud.asdfmydomain.com/MyCloudService, которые могут принять сообщение. Это часто вызвано неправильным адресом или действием SOAP. См. InnerException, если имеется, для более подробной информации. "

InnerException:

"Удаленный сервер возвратил ошибку: (404) Not Found."

Add Service Reference из Visual Studio 2017 сказали то же самое.

Я получил похожий код, работающий из моей службы Windows, поэтому, возможно, проблема в том, что я пересекаю компьютер, возможно, порты, возможно, брандмауэр в учетной записи хостинга и т. Д.

Некоторые (но не все) ссылки:

Мысли

ОБНОВЛЕНИЕ НА ОСНОВЕ ОТВЕТА 1:

(Так что я должен заплатить мне боль и страдания за то, что мне пришлось терпеть эту чрезвычайно раздражающую тему празднования Первоапрельского. Я пытаюсь сосредоточиться на программировании и оставаться сосредоточенным.)

Я делаю успехи, еще не играю в кости.

Мой сервис не обнаружил сообщение об ошибке и дублировал MyCloud.Communication.MyCloud, а не MyCLoud.Communication.CloudService сообщение об ошибке было результатом неполного рефакторинга со стороны Visual Studio. Visual Studio НЕ реорганизовал файл разметки .SVC.

<%@ ServiceHost Language="C#" Debug="true" Service="MyCloud.Communication.CloudService" CodeBehind="CloudService.svc.cs" %>

Указание в браузере следующего URL дает:

http://mycloud.asdfmydomain.com/Communication/CloudService.svc/Address1

Вот ключевая часть URL ссылки Microsoft :

или вы можете предоставить базовый адрес для ServiceHost службы, а затем указать адрес для каждой конечной точки, связанной с этой службой, который определен относительно этого базового адреса. Путь: /mathservice.svc/secureEndpoint

Мне пришлось удалить закомментированный <serviceHostingEnvironment, потому что браузер хотел multipleSiteBindingsEnabled="true".

В тексте говорится, что первой частью URI является path to the SVC file, за которым следует endpoint address name, указанный в теге EndPointAddres.

Ошибка через Chrome:

[ServiceActivationException: The service '/Communication/CloudService.svc' cannot be activated due to an exception during compilation.  The exception message is: The endpoint at 'http://mycloud.asdfmydomain.com/Communication/CloudService.svc/Address1' does not have a Binding with the None MessageVersion.  'System.ServiceModel.Description.WebHttpBehavior' is only intended for use with WebHttpBinding or similar bindings..]

Ошибка через C #:

{"The requested service, 'http://mycloud.asdfmydomain.com/Communication/CloudService.svc/Address1' could not be activated. See the server's diagnostic trace logs for more information."}

Я делаю успехи.

1 Ответ

0 голосов
/ 01 апреля 2019

В вашем web.config вы пишете

 <baseAddresses>
                    <add baseAddress="http://localhost/MyCloudService/"/>
                </baseAddresses>

Когда вы звоните в службу, адрес равен http://Mycloud.asdfmydomain.com/MyCloudService, что не соответствует конфигурации адреса в вашем web.config.

Если вы не уверены, какой адрес вашего сервиса, вы можете увидеть его через wsdl.

Например, мой web.config

<service name="Service.CalculatorService" >
    <endpoint address="Calculator.svc/abc/" binding="basicHttpBinding"  contract="ServiceInterface.ICalculatorService" ></endpoint>
   <host>
      <baseAddresses>
        <add baseAddress="http://localhost:62193/"/>
      </baseAddresses>
    </host>
  </service>

Тогда, когда я введу адрес моегоwsdl-адрес службы http://localhost:62193/Calculator.svc?singleWsdl.

Я мог найти адрес своей службы через wsdl внизу.enter image description here

Вы могли видеть, даже если я пишу только один Calculator.svc, есть еще два Calculator.svc.

Поскольку базовый адрес будет сначала объединен с вашим svcа затем в сочетании с относительным адресом.Таким образом, конечный адрес будет baseaddree + svc + относительный адрес.

Пожалуйста, обратитесь к ссылке ниже WCF :lativeAddress, baseAddress и binding

...