WCF Self-Host для доступа из Интернета - PullRequest
0 голосов
/ 05 августа 2020

Я пытаюсь создать службу для ее использования через inte rnet, но по какой-то причине я не могу получить к ней доступ, и мне нужна помощь в поиске ошибки, которую я делаю. Я оставляю код для вашего просмотра.

 public class ServiceHost<T> : System.ServiceModel.ServiceHost
    {

        public ServiceHost(Type serviceType, params Uri[] baseAddresses)
            : base(serviceType, baseAddresses)
        {
        }

        public ServiceHost(object singletonInstance, params Uri[] baseAddresses)
            :base(singletonInstance, baseAddresses)
        {

        }
        protected ServiceHost() 
            : base()
        {

        }
        public void EnableMetadataExchange(bool enableHttpGet = true)
        {
            if (State == CommunicationState.Opened)
            {
                throw new InvalidOperationException("La comunicación ya está abierta");
            }
            ServiceMetadataBehavior metadataBehavior
                                = Description.Behaviors.Find<ServiceMetadataBehavior>();

            if (metadataBehavior == null)
            {
                metadataBehavior = new ServiceMetadataBehavior();
                Description.Behaviors.Add(metadataBehavior);

                if (BaseAddresses.Any(uri => uri.Scheme == "http"))
                    metadataBehavior.HttpGetEnabled = enableHttpGet;
                }
            AddAllMexEndPoints();
        }
        public bool HasMexEndpoint
        {
            get
            {
                return Description.Endpoints.Any(
                                              endpoint => endpoint.Contract.ContractType ==
                                              typeof(IMetadataExchange));
            }
        }

        private void AddAllMexEndPoints()
        {
            Debug.Assert(HasMexEndpoint == false);
            foreach (Uri baseAddress in BaseAddresses)
            {
                Binding binding = null;

                switch (baseAddress.Scheme)
                {
                    case "net.tcp":
                        {
                            binding = MetadataExchangeBindings.CreateMexTcpBinding();
                            break;
                        }
                    case "http":
                        {
                            binding = MetadataExchangeBindings.CreateMexHttpBinding();
                            break;
                        }
                    case "https":
                        {
                            binding = MetadataExchangeBindings.CreateMexHttpsBinding();
                            break;
                        }
                    case "net.pipe":
                        {
                            binding = MetadataExchangeBindings.CreateMexNamedPipeBinding();
                            break;
                        }
                }
                if (binding != null)
                {
                    AddServiceEndpoint(typeof(IMetadataExchange), binding, "MEX");
                }
            }
        }
    }

Хостинг

        public void HostService()
    {
        try
        {
            Uri tcpBaseAddress = new Uri("net.tcp://192.168.1.110:28620/");
            Uri httpBaseAddress = new Uri("http://192.168.1.110:28621/");
            ServiceHost<wesling.Services.GC> host = new ServiceHost<wesling.Services.GC>(typeof(wesling.Services.GC), tcpBaseAddress, httpBaseAddress);
            //add tcp binding
            var netTcpBinding = new NetTcpBinding()
            {
                MaxBufferPoolSize = int.MaxValue,
                MaxReceivedMessageSize = int.MaxValue,
                ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas()
                {
                    MaxStringContentLength = int.MaxValue
                },
            };
            netTcpBinding.Security.Mode = SecurityMode.None;
            host.AddServiceEndpoint(typeof(wesling.Services.IGC), netTcpBinding, "GC");

            //add WSHttp binding
            var httpBinding = new WSHttpBinding()
            {
                MaxBufferPoolSize = int.MaxValue,
                MaxReceivedMessageSize = int.MaxValue,
                ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas()
                {
                    MaxStringContentLength = int.MaxValue
                },
            };
            httpBinding.Security.Mode = SecurityMode.None;
            host.AddServiceEndpoint(typeof(wesling.Services.IGC), httpBinding, "GC");

            host.EnableMetadataExchange(true);
            host.Open();
        }
        catch (CommunicationException ce)
        {
            MessageBox.Show(ce.Message);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

uri ip - это lan ip для p c где размещена служба

Заказчик такой

public async void GetProduct()
        {
            try
            {

                var endPointConfiguration = "WSHttpBinding_IGC";//cfg.GetEndPointConfiguration();
                var address = "http://fabianwesling.dynu.com:28621/GC"; //cfg.getAddress();

                ServiceReference1.GCClient service = new ServiceReference1.GCClient(endPointConfiguration, address);
                var bindins = service.Endpoint.Binding;
                if (bindins is NetTcpBinding tcpBinding)
                {
                    tcpBinding.MaxBufferPoolSize = int.MaxValue;
                    tcpBinding.MaxReceivedMessageSize = int.MaxValue;
                    tcpBinding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
                }
                else if (bindins is WSHttpBinding wS)
                {
                    wS.MaxBufferPoolSize = int.MaxValue;
                    wS.MaxReceivedMessageSize = int.MaxValue;
                    wS.ReaderQuotas.MaxStringContentLength = int.MaxValue;
                }

             var result =  await service.GetProductsAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

Я открыл порты в Reuter, чтобы он направлял эти порты к p c, и я также открыл порты в брандмауэре, я также активировал функции Windows. net framework. Но когда я пытаюсь подключиться к клиенту, он говорит мне, что прослушивания не было конца. Должна быть какая-то концепция, которую я не понимаю, но я не могу определить, что это ... Мне нужен ваш совет, все приветствуются

1 Ответ

0 голосов
/ 06 августа 2020

Сначала попробуйте использовать браузер на клиентском компьютере, чтобы посетить http // fabianwesling.dynu.com: 28621 / G C, чтобы проверить, можно ли получить доступ к метаданным в обычном режиме. Если нет, то клиент и сервер не могут получить нормальный доступ . Измените файл hots на клиентском компьютере:

enter image description here

All in all, you must ensure that the client and server are mutually accessible on the Internet.

If it is not a network problem, you can create a simple WCF service for testing to know where the problem is.Here is a very simple example of WCF service:

https://docs.microsoft.com/en-us/dotnet/framework/wcf/getting-started-tutorial

ОБНОВЛЕНИЕ

Это мой пульт Служба WCF:

enter image description here

Baseadress is the WAN IP.

Ensure that the local computer can access the WSDL of the remote service through a browser

введите описание изображения здесь

...