public void Open()
        {
            HttpBinding binding = new HttpBinding();
            this.ChannelListener = binding.BuildChannelListener<IReplyChannel>(this.BaseAddress);
            this.ChannelListener.Open();

            IReplyChannel channnel = this.ChannelListener.AcceptChannel();
            channnel.Open();

            while (true)
            {
                RequestContext requestContext = channnel.ReceiveRequest(TimeSpan.MaxValue);
                Message message = requestContext.RequestMessage;
                MethodInfo method = message.GetType().GetMethod("GetHttpRequestMessage");
                HttpRequestMessage request = (HttpRequestMessage)method.Invoke(message, new object[] { true });
                Task<HttpResponseMessage> processResponse = base.SendAsync(request, new CancellationTokenSource().Token);
                processResponse.ContinueWith(task =>
                    {
                        string httpMessageTypeName = "System.Web.Http.SelfHost.Channels.HttpMessage, System.Web.Http.SelfHost";
                        Type httpMessageType = Type.GetType(httpMessageTypeName);
                        Message reply = (Message)Activator.CreateInstance(httpMessageType, new object[] { task.Result });
                        requestContext.Reply(reply);
                    });
            }
        }
        public HttpBindingController()
        {

            HttpBinding httpBinding = new HttpBinding();


        }
 protected override BindingParameterCollection OnConfigureBinding(HttpBinding httpBinding)
 {
     httpBinding.Security.Mode = HttpBindingSecurityMode.TransportCredentialOnly;
     httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
     this.UserNamePasswordValidator = _functionalUserNamePasswordValidator;
     return base.OnConfigureBinding(httpBinding);
 }
        /// <summary>
        /// Called to apply the configuration on the endpoint level.
        /// </summary>
        /// <param name="httpBinding">The HTTP endpoint.</param>
        /// <returns>
        /// The <see cref="T:System.ServiceModel.Channels.BindingParameterCollection" /> to use when building the <see cref="T:System.ServiceModel.Channels.IChannelListener" /> or null if no binding parameters are present.
        /// </returns>
        protected override System.ServiceModel.Channels.BindingParameterCollection OnConfigureBinding(HttpBinding httpBinding)
        {
            if (_requiresSSL)
            {
                httpBinding.Security.Mode = HttpBindingSecurityMode.Transport;
            }

            var binding = base.OnConfigureBinding(httpBinding);
            return binding;
        }
예제 #5
0
파일: Program.cs 프로젝트: on-looker/DTest
 static void Main(string[] args)
 {
     Assembly.Load("BlankWebApi");
     HttpSelfHostConfiguration configuration=new HttpSelfHostConfiguration("http://localhost/selfhost");
     using (HttpSelfHostServer server = new HttpSelfHostServer(configuration))
     {
         server.Configuration.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
        );
         server.OpenAsync();
         Console.ReadKey();
     }
     HttpBinding binding=new HttpBinding();
 }
        static void Main(string[] args)
        {
            Uri listenUri = new Uri("http://127.0.0.1:3721");
            Binding binding = new HttpBinding();

            //创建、开启信道监听器
            IChannelListener<IReplyChannel> channelListener = binding.BuildChannelListener<IReplyChannel>(listenUri);   //调用BuildChannelListener<IReplyChannel>方法创建一个channelListener管道
            channelListener.Open();

            //创建、开启回复信道
            IReplyChannel channel = channelListener.AcceptChannel(TimeSpan.MaxValue);
            channel.Open();

            //开始监听
            while (true)
            {
                //接收输出请求消息
                RequestContext requestContext =
                    channel.ReceiveRequest(TimeSpan.MaxValue);
                PrintRequestMessage(requestContext.RequestMessage);
                //消息回复
                requestContext.Reply(CreateResponseMessage());
            }
        }
        public void HttpSelfHostConfiguration_WrongClientCredentialType_WithUsernamePasswordValidator_Throws(string address, HttpBindingSecurityMode mode, HttpClientCredentialType clientCredentialType)
        {
            // Arrange
            HttpBinding binding = new HttpBinding();
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address)
            {
                UserNamePasswordValidator = new CustomUsernamePasswordValidator()
            };

            config.ClientCredentialType = clientCredentialType;

            Assert.Throws<InvalidOperationException>(() =>
                {
                    // Act
                    BindingParameterCollection parameters = config.ConfigureBinding(binding);
                });
        }
        public void HttpSelfHostConfiguration_ClientCredentialType_PropagatesToHttpBinding(string address, HttpBindingSecurityMode mode, HttpClientCredentialType clientCredentialType)
        {
            // Arrange
            HttpBinding binding = new HttpBinding();
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address)
            {
                ClientCredentialType = clientCredentialType
            };

            // Act
            BindingParameterCollection parameters = config.ConfigureBinding(binding);

            Assert.Equal(clientCredentialType, binding.Security.Transport.ClientCredentialType);
            Assert.Equal(mode, binding.Security.Mode);
        }
        public void HttpSelfHostConfiguration_Settings_PropagateToBinding()
        {
            // Arrange
            HttpBinding binding = new HttpBinding();
            binding.ConfigureTransportBindingElement = ConfigureTransportBindingElement;
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration("http://localhost")
            {
                MaxBufferSize = 10,
                MaxReceivedMessageSize = 11,
                ReceiveTimeout = new TimeSpan(1, 0, 0),
                SendTimeout = new TimeSpan(1, 0, 0),
                TransferMode = TransferMode.StreamedResponse,
                HostNameComparisonMode = HostNameComparisonMode.WeakWildcard
            };

            // Act
            config.ConfigureBinding(binding);

            // Assert
            Assert.Equal(10, binding.MaxBufferSize);
            Assert.Equal(11, binding.MaxReceivedMessageSize);
            Assert.Equal(new TimeSpan(1, 0, 0), binding.ReceiveTimeout);
            Assert.Equal(new TimeSpan(1, 0, 0), binding.SendTimeout);
            Assert.Equal(TransferMode.StreamedResponse, binding.TransferMode);
            Assert.Equal(HostNameComparisonMode.WeakWildcard, binding.HostNameComparisonMode);
            Assert.Equal(Net.AuthenticationSchemes.Ntlm, binding.CreateBindingElements().Find<HttpTransportBindingElement>().AuthenticationScheme);
        }
 protected override BindingParameterCollection OnConfigureBinding(HttpBinding httpBinding)
 {
     httpBinding.Security.Mode = HttpBindingSecurityMode.TransportCredentialOnly;
     httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
     return base.OnConfigureBinding(httpBinding);
 }
        public void HttpSelfHostConfiguration_CorrectClientCredentialType_WithX509CertificateValidator_Works(string address, HttpBindingSecurityMode mode, HttpClientCredentialType clientCredentialType)
        {
            // Arrange
            HttpBinding binding = new HttpBinding();
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address)
            {
                X509CertificateValidator = new Mock<X509CertificateValidator>().Object
            };

            config.ClientCredentialType = clientCredentialType;

            // Act
            BindingParameterCollection parameters = config.ConfigureBinding(binding);
        }
        /// <summary>
        /// Called to apply the configuration on the endpoint level.
        /// </summary>
        /// <param name="httpBinding">Http endpoint.</param>
        /// <returns>The <see cref="BindingParameterCollection"/> to use when building the <see cref="IChannelListener"/> or null if no binding parameters are present.</returns>
        protected virtual BindingParameterCollection OnConfigureBinding(HttpBinding httpBinding)
        {
            if (httpBinding == null)
            {
                throw Error.ArgumentNull("httpBinding");
            }

            if (_useWindowsAuth && _credentials.UserNameAuthentication.CustomUserNamePasswordValidator != null)
            {
                throw Error.InvalidOperation(SRResources.CannotUseWindowsAuthWithUserNamePasswordValidator);
            }

            httpBinding.MaxBufferSize = MaxBufferSize;
            httpBinding.MaxReceivedMessageSize = MaxReceivedMessageSize;
            httpBinding.TransferMode = TransferMode;
            httpBinding.HostNameComparisonMode = HostNameComparisonMode;

            if (_baseAddress.Scheme == Uri.UriSchemeHttps)
            {
                // we need to use SSL
                httpBinding.Security = new HttpBindingSecurity()
                {
                    Mode = HttpBindingSecurityMode.Transport,
                };
            }

            // Set up binding parameters
            if (_credentials.UserNameAuthentication.CustomUserNamePasswordValidator != null)
            {
                _credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
                if (httpBinding.Security == null || httpBinding.Security.Mode == HttpBindingSecurityMode.None)
                {
                    // Basic over HTTP case
                    httpBinding.Security = new HttpBindingSecurity()
                    {
                        Mode = HttpBindingSecurityMode.TransportCredentialOnly,
                    };
                }

                // We have validator, so we can set the client credential type to be basic
                httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;

                return AddCredentialsToBindingParameters();
            }
            else if (_useWindowsAuth)
            {
                if (httpBinding.Security == null || httpBinding.Security.Mode == HttpBindingSecurityMode.None)
                {
                    // Basic over HTTP case, should we even allow this?
                    httpBinding.Security = new HttpBindingSecurity()
                    {
                        Mode = HttpBindingSecurityMode.TransportCredentialOnly,
                    };
                }

                // We have validator, so we can set the client credential type to be windows
                httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;

                return AddCredentialsToBindingParameters();
            }

            return null;
        }
 /// <summary>
 /// Internal method called to configure <see cref="HttpBinding"/> settings.
 /// </summary>
 /// <param name="httpBinding">Http binding.</param>
 /// <returns>The <see cref="BindingParameterCollection"/> to use when building the <see cref="IChannelListener"/> or null if no binding parameters are present.</returns>
 internal BindingParameterCollection ConfigureBinding(HttpBinding httpBinding)
 {
     return OnConfigureBinding(httpBinding);
 }
예제 #14
0
 protected override System.ServiceModel.Channels.BindingParameterCollection OnConfigureBinding(System.Web.Http.SelfHost.Channels.HttpBinding httpBinding)
 {
     httpBinding.Security.Mode = HttpBindingSecurityMode.TransportCredentialOnly;
     httpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
     return(base.OnConfigureBinding(httpBinding));
 }
        public void HttpSelfHostConfiguration_CorrectClientCredentialType_WithUsernamePasswordValidator_Works(string address, HttpBindingSecurityMode mode, HttpClientCredentialType clientCredentialType)
        {
            // Arrange
            HttpBinding binding = new HttpBinding();
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address)
            {
                UserNamePasswordValidator = new CustomUsernamePasswordValidator()
            };

            config.ClientCredentialType = clientCredentialType;

            // Act
            BindingParameterCollection parameters = config.ConfigureBinding(binding);
        }
예제 #16
0
        private void BeginOpenListener(HttpSelfHostServer server)
        {
            Contract.Assert(server != null);

            try
            {
                // Create WCF HTTP transport channel
                HttpBinding binding = new HttpBinding();

                // Get it configured
                BindingParameterCollection bindingParameters = server._configuration.ConfigureBinding(binding);
                if (bindingParameters == null)
                {
                    bindingParameters = new BindingParameterCollection();
                }

                // Build channel listener
                server._listener = binding.BuildChannelListener<IReplyChannel>(server._configuration.BaseAddress, bindingParameters);
                if (server._listener == null)
                {
                    throw Error.InvalidOperation(SRResources.InvalidChannelListener, typeof(IChannelListener).Name, typeof(IReplyChannel).Name);
                }

                IAsyncResult result = server._listener.BeginOpen(_onOpenListenerComplete, server);
                if (result.CompletedSynchronously)
                {
                    OpenListenerComplete(result);
                }
            }
            catch (Exception e)
            {
                FaultTask(server._openTaskCompletionSource, e);
            }
        }
        public void HttpSelfHostConfiguration_WrongClientCredentialType_WithX509CertificateValidator_Throws(string address, HttpBindingSecurityMode mode, HttpClientCredentialType clientCredentialType)
        {
            // Arrange
            HttpBinding binding = new HttpBinding();
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address)
            {
                X509CertificateValidator = new Mock<X509CertificateValidator>().Object
            };

            config.ClientCredentialType = clientCredentialType;

            Assert.Throws<InvalidOperationException>(() =>
            {
                // Act
                BindingParameterCollection parameters = config.ConfigureBinding(binding);
            });
        }
        public void HttpSelfHostConfiguration_Settings_PropagateToBinding()
        {
            // Arrange
            HttpBinding binding = new HttpBinding();
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration("http://localhost")
            {
                MaxBufferSize = 10,
                MaxReceivedMessageSize = 11,
                TransferMode = TransferMode.StreamedResponse,
                HostNameComparisonMode = HostNameComparisonMode.WeakWildcard
            };

            // Act
            config.ConfigureBinding(binding);

            // Assert
            Assert.Equal(10, binding.MaxBufferSize);
            Assert.Equal(11, binding.MaxReceivedMessageSize);
            Assert.Equal(TransferMode.StreamedResponse, binding.TransferMode);
            Assert.Equal(HostNameComparisonMode.WeakWildcard, binding.HostNameComparisonMode);
        }
        public void HttpSelfHostConfiguration_UserNamePasswordValidator_PropagatesToBinding(string address, HttpBindingSecurityMode mode)
        {
            // Arrange
            HttpBinding binding = new HttpBinding();
            UserNamePasswordValidator validator = new Mock<UserNamePasswordValidator>().Object;
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address)
            {
                UserNamePasswordValidator = validator
            };

            // Act
            BindingParameterCollection parameters = config.ConfigureBinding(binding);

            // Assert
            Assert.NotNull(parameters);
            ServiceCredentials serviceCredentials = parameters.Find<ServiceCredentials>();
            Assert.NotNull(serviceCredentials);
            Assert.Equal(HttpClientCredentialType.Basic, binding.Security.Transport.ClientCredentialType);
            Assert.Equal(mode, binding.Security.Mode);
        }
        public void HttpSelfHostConfiguration_UseWindowsAuth_PropagatesToHttpBinding(string address, HttpBindingSecurityMode mode)
        {
            // Arrange
            HttpBinding binding = new HttpBinding();
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(address)
            {
                UseWindowsAuthentication = true
            };

            // Act
            BindingParameterCollection parameters = config.ConfigureBinding(binding);

            // Assert
            Assert.NotNull(parameters);
            ServiceCredentials serviceCredentials = parameters.Find<ServiceCredentials>();
            Assert.NotNull(serviceCredentials);
            Assert.Equal(HttpClientCredentialType.Windows, binding.Security.Transport.ClientCredentialType);
            Assert.Equal(mode, binding.Security.Mode);
        }
 protected override BindingParameterCollection OnConfigureBinding(HttpBinding httpBinding)
 {
     httpBinding.Security.Mode = HttpBindingSecurityMode.Transport;
     return base.OnConfigureBinding(httpBinding);
 }
        /// <summary>
        /// Called to apply the configuration on the endpoint level.
        /// </summary>
        /// <param name="httpBinding">Http endpoint.</param>
        /// <returns>The <see cref="BindingParameterCollection"/> to use when building the <see cref="IChannelListener"/> or null if no binding parameters are present.</returns>
        protected virtual BindingParameterCollection OnConfigureBinding(HttpBinding httpBinding)
        {
            if (httpBinding == null)
            {
                throw Error.ArgumentNull("httpBinding");
            }

            if (_clientCredentialType != HttpClientCredentialType.Basic && _credentials.UserNameAuthentication.CustomUserNamePasswordValidator != null)
            {
                throw Error.InvalidOperation(SRResources.CannotUseOtherClientCredentialTypeWithUserNamePasswordValidator);
            }

            if (_clientCredentialType != HttpClientCredentialType.Certificate && _credentials.ClientCertificate.Authentication.CustomCertificateValidator != null)
            {
                throw Error.InvalidOperation(SRResources.CannotUseOtherClientCredentialTypeWithX509CertificateValidator);
            }

            httpBinding.MaxBufferSize = MaxBufferSize;
            httpBinding.MaxReceivedMessageSize = MaxReceivedMessageSize;
            httpBinding.TransferMode = TransferMode;
            httpBinding.HostNameComparisonMode = HostNameComparisonMode;
            httpBinding.ReceiveTimeout = ReceiveTimeout;
            httpBinding.SendTimeout = SendTimeout;

            // Set up binding parameters
            if (_baseAddress.Scheme == Uri.UriSchemeHttps)
            {
                // we need to use SSL
                httpBinding.Security = new HttpBindingSecurity()
                {
                    Mode = HttpBindingSecurityMode.Transport,
                };
            }
            
            if (_clientCredentialType != HttpClientCredentialType.None)
            {       
                if (httpBinding.Security == null || httpBinding.Security.Mode == HttpBindingSecurityMode.None)
                {
                    // Basic over HTTP case
                    httpBinding.Security = new HttpBindingSecurity()
                    {
                        Mode = HttpBindingSecurityMode.TransportCredentialOnly,
                    };
                }

                httpBinding.Security.Transport.ClientCredentialType = _clientCredentialType;                
            }

            if (UserNamePasswordValidator != null || X509CertificateValidator != null)
            {
                // those are the only two things that affect service credentials
                return AddCredentialsToBindingParameters();
            }
            else
            {
                return null;
            }
        }