Exemple #1
0
        private static HttpMessageHandlerOptions CreateOptions(
            IAppBuilder builder,
            HttpServer server,
            HttpConfiguration configuration
            )
        {
            Contract.Assert(builder != null);
            Contract.Assert(server != null);
            Contract.Assert(configuration != null);

            ServicesContainer services = configuration.Services;

            Contract.Assert(services != null);

            IHostBufferPolicySelector bufferPolicySelector =
                services.GetHostBufferPolicySelector() ?? _defaultBufferPolicySelector;
            IExceptionLogger  exceptionLogger  = ExceptionServices.GetLogger(services);
            IExceptionHandler exceptionHandler = ExceptionServices.GetHandler(services);

            return(new HttpMessageHandlerOptions
            {
                MessageHandler = server,
                BufferPolicySelector = bufferPolicySelector,
                ExceptionLogger = exceptionLogger,
                ExceptionHandler = exceptionHandler,
                AppDisposing = builder.GetOnAppDisposingProperty()
            });
        }
        // Provides HttpMessageHandlerOptions for callers using the old constructor.
        private static HttpMessageHandlerOptions CreateOptions(
            HttpMessageHandler messageHandler,
            IHostBufferPolicySelector bufferPolicySelector
            )
        {
            if (messageHandler == null)
            {
                throw new ArgumentNullException("messageHandler");
            }

            if (bufferPolicySelector == null)
            {
                throw new ArgumentNullException("bufferPolicySelector");
            }

            // Callers using the old constructor get the default exception handler, no exception logging support, and no
            // app cleanup support.

            return(new HttpMessageHandlerOptions
            {
                MessageHandler = messageHandler,
                BufferPolicySelector = bufferPolicySelector,
                ExceptionLogger = new EmptyExceptionLogger(),
                ExceptionHandler = new DefaultExceptionHandler(),
                AppDisposing = CancellationToken.None
            });
        }
 public HttpMessageHandlerAdapter(
     OwinMiddleware next,
     HttpMessageHandler messageHandler,
     IHostBufferPolicySelector bufferPolicySelector
     ) : this(next, CreateOptions(messageHandler, bufferPolicySelector))
 {
 }
    public static IAppBuilder UseWebApi(this IAppBuilder builder,
                                        HttpConfiguration configuration,
                                        Func <HttpRequestMessage, HttpResponseMessage, bool> callNextPolicy)
    {
        IHostBufferPolicySelector bufferPolicySelector = configuration.Services.GetHostBufferPolicySelector() ?? _defaultBufferPolicySelector;

        return(builder.Use(typeof(HttpMessageHandlerAdapterModified), new HttpServer(configuration), bufferPolicySelector, callNextPolicy));
    }
Exemple #5
0
        internal static HttpRequestMessage ConvertRequest(HttpContextBase httpContextBase)
        {
            Contract.Assert(httpContextBase != null);

            HttpRequestBase    requestBase = httpContextBase.Request;
            HttpMethod         method      = HttpMethodHelper.GetHttpMethod(requestBase.HttpMethod);
            Uri                uri         = requestBase.Url;
            HttpRequestMessage request     = new HttpRequestMessage(method, uri);

            // Choose a buffered or bufferless input stream based on user's policy
            IHostBufferPolicySelector policySelector = _bufferPolicySelector.Value;
            bool isInputBuffered = policySelector == null ? true : policySelector.UseBufferedInputStream(httpContextBase);

            if (isInputBuffered)
            {
                request.Content = new LazyStreamContent(() => requestBase.InputStream);
            }
            else
            {
                request.Content = new LazyStreamContent(() => requestBase.GetBufferlessInputStream());
            }

            foreach (string headerName in requestBase.Headers)
            {
                string[] values = requestBase.Headers.GetValues(headerName);
                AddHeaderToHttpRequestMessage(request, headerName, values);
            }

            // Add context to enable route lookup later on
            request.SetHttpContext(httpContextBase);

            HttpRequestContext requestContext = new WebHostHttpRequestContext(httpContextBase, requestBase, request);

            request.SetRequestContext(requestContext);

            IDictionary httpContextItems = httpContextBase.Items;

            // Add the OWIN environment, when available (such as when using the OWIN integrated pipeline HTTP module).
            if (httpContextItems != null && httpContextItems.Contains(OwinEnvironmentHttpContextKey))
            {
                request.Properties.Add(OwinEnvironmentKey, httpContextItems[OwinEnvironmentHttpContextKey]);
            }

            // The following three properties are set for backwards compatibility only. The request context controls
            // the behavior for all cases except when accessing the property directly by key.

            // Add the retrieve client certificate delegate to the property bag to enable lookup later on
            request.Properties.Add(HttpPropertyKeys.RetrieveClientCertificateDelegateKey, _retrieveClientCertificate);

            // Add information about whether the request is local or not
            request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy <bool>(() => requestBase.IsLocal));

            // Add information about whether custom errors are enabled for this request or not
            request.Properties.Add(HttpPropertyKeys.IncludeErrorDetailKey, new Lazy <bool>(() => !httpContextBase.IsCustomErrorEnabled));

            return(request);
        }
        public void BufferPolicySelectorGet_ReturnsSpecifiedInstance()
        {
            // Arrange
            HttpMessageHandlerOptions product = CreateProductUnderTest();
            IHostBufferPolicySelector expectedBufferPolicySelector = CreateDummyBufferPolicy();

            product.BufferPolicySelector = expectedBufferPolicySelector;

            // Act
            IHostBufferPolicySelector bufferPolicy = product.BufferPolicySelector;

            // Assert
            Assert.Same(expectedBufferPolicySelector, bufferPolicy);
        }
        public HttpMessageHandlerAdapter(OwinMiddleware next, HttpMessageHandler messageHandler, IHostBufferPolicySelector bufferPolicySelector)
            : base(next)
        {
            if (messageHandler == null)
            {
                throw new ArgumentNullException("messageHandler");
            }
            if (bufferPolicySelector == null)
            {
                throw new ArgumentNullException("bufferPolicySelector");
            }

            _messageInvoker       = new HttpMessageInvoker(messageHandler);
            _bufferPolicySelector = bufferPolicySelector;
        }
        public HttpMessageHandlerAdapter(OwinMiddleware next, HttpMessageHandler messageHandler, IHostBufferPolicySelector bufferPolicySelector)
            : base(next)
        {
            if (messageHandler == null)
            {
                throw new ArgumentNullException("messageHandler");
            }
            if (bufferPolicySelector == null)
            {
                throw new ArgumentNullException("bufferPolicySelector");
            }

            _messageInvoker = new HttpMessageInvoker(messageHandler);
            _bufferPolicySelector = bufferPolicySelector;
        }
Exemple #9
0
        /// <summary>Initializes a new instance of the <see cref="HttpMessageHandlerAdapter"/> class.</summary>
        /// <param name="next">The next component in the pipeline.</param>
        /// <param name="options">The options to configure this adapter.</param>
        public HttpMessageHandlerAdapter(OwinMiddleware next, HttpMessageHandlerOptions options)
            : base(next)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            _messageHandler = options.MessageHandler;

            if (_messageHandler == null)
            {
                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,
                                                         typeof(HttpMessageHandlerOptions).Name, "MessageHandler"), "options");
            }

            _messageInvoker       = new HttpMessageInvoker(_messageHandler);
            _bufferPolicySelector = options.BufferPolicySelector;

            if (_bufferPolicySelector == null)
            {
                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,
                                                         typeof(HttpMessageHandlerOptions).Name, "BufferPolicySelector"), "options");
            }

            _exceptionLogger = options.ExceptionLogger;

            if (_exceptionLogger == null)
            {
                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,
                                                         typeof(HttpMessageHandlerOptions).Name, "ExceptionLogger"), "options");
            }

            _exceptionHandler = options.ExceptionHandler;

            if (_exceptionHandler == null)
            {
                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,
                                                         typeof(HttpMessageHandlerOptions).Name, "ExceptionHandler"), "options");
            }

            _appDisposing = options.AppDisposing;

            if (_appDisposing.CanBeCanceled)
            {
                _appDisposing.Register(OnAppDisposing);
            }
        }
        /// <summary>Initializes a new instance of the <see cref="HttpMessageHandlerAdapter"/> class.</summary>
        /// <param name="next">The next component in the pipeline.</param>
        /// <param name="options">The options to configure this adapter.</param>
        public HttpMessageHandlerAdapter(OwinMiddleware next, HttpMessageHandlerOptions options)
            : base(next)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            _messageHandler = options.MessageHandler;

            if (_messageHandler == null)
            {
                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,
                    typeof(HttpMessageHandlerOptions).Name, "MessageHandler"), "options");
            }

            _messageInvoker = new HttpMessageInvoker(_messageHandler);
            _bufferPolicySelector = options.BufferPolicySelector;

            if (_bufferPolicySelector == null)
            {
                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,
                    typeof(HttpMessageHandlerOptions).Name, "BufferPolicySelector"), "options");
            }

            _exceptionLogger = options.ExceptionLogger;

            if (_exceptionLogger == null)
            {
                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,
                    typeof(HttpMessageHandlerOptions).Name, "ExceptionLogger"), "options");
            }

            _exceptionHandler = options.ExceptionHandler;

            if (_exceptionHandler == null)
            {
                throw new ArgumentException(Error.Format(OwinResources.TypePropertyMustNotBeNull,
                    typeof(HttpMessageHandlerOptions).Name, "ExceptionHandler"), "options");
            }

            _appDisposing = options.AppDisposing;

            if (_appDisposing.CanBeCanceled)
            {
                _appDisposing.Register(OnAppDisposing);
            }
        }
Exemple #11
0
        public HttpMessageHandlerAdapter(AppFunc next, HttpMessageHandler messageHandler, IHostBufferPolicySelector bufferPolicySelector)
        {
            if (next == null)
            {
                throw new ArgumentNullException("next");
            }
            if (messageHandler == null)
            {
                throw new ArgumentNullException("messageHandler");
            }
            if (bufferPolicySelector == null)
            {
                throw new ArgumentNullException("bufferPolicySelector");
            }

            _next                 = next;
            _messageInvoker       = new HttpMessageInvoker(messageHandler);
            _bufferPolicySelector = bufferPolicySelector;
        }
        public HttpMessageHandlerAdapterModified(OwinMiddleware next,
                                                 HttpMessageHandler messageHandler,
                                                 IHostBufferPolicySelector bufferPolicySelector,
                                                 Func <HttpRequestMessage, HttpResponseMessage, bool> callNextPolicy)
            : base(next)
        {
            _callNextPolicy = callNextPolicy;
            if (messageHandler == null)
            {
                throw new ArgumentNullException("messageHandler");
            }
            if (bufferPolicySelector == null)
            {
                throw new ArgumentNullException("bufferPolicySelector");
            }

            _messageInvoker       = new HttpMessageInvoker(messageHandler);
            _bufferPolicySelector = bufferPolicySelector;
        }
        public HttpMessageHandlerAdapter(AppFunc next, HttpMessageHandler messageHandler, IHostBufferPolicySelector bufferPolicySelector)
        {
            if (next == null)
            {
                throw new ArgumentNullException("next");
            }
            if (messageHandler == null)
            {
                throw new ArgumentNullException("messageHandler");
            }
            if (bufferPolicySelector == null)
            {
                throw new ArgumentNullException("bufferPolicySelector");
            }

            _next = next;
            _messageInvoker = new HttpMessageInvoker(messageHandler);
            _bufferPolicySelector = bufferPolicySelector;
        }
        private static HttpMessageHandlerOptions CreateOptions(HttpMessageHandler messageHandler,
                                                               IHostBufferPolicySelector bufferPolicySelector)
        {
            if (messageHandler == null)
            {
                throw new ArgumentNullException("messageHandler");
            }

            if (bufferPolicySelector == null)
            {
                throw new ArgumentNullException("bufferPolicySelector");
            }

            return(new HttpMessageHandlerOptions
            {
                MessageHandler = messageHandler,
                BufferPolicySelector = bufferPolicySelector,
                ExceptionLogger = new EmptyExceptionLogger(),
                ExceptionHandler = new DefaultExceptionHandler()
            });
        }
        public HttpMessageHandlerAdapter(RequestDelegate next, HttpMessageHandlerOptions options, IHostApplicationLifetime applicationLifetime)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            _next                 = next;
            _messageHandler       = options.MessageHandler ?? throw new ArgumentNullException(nameof(options.MessageHandler));
            _messageInvoker       = new HttpMessageInvoker(_messageHandler);
            _bufferPolicySelector = options.BufferPolicySelector ?? throw new ArgumentNullException(nameof(options.BufferPolicySelector));

            _exceptionLogger  = options.ExceptionLogger;
            _exceptionHandler = options.ExceptionHandler;

            if (applicationLifetime.ApplicationStopping.CanBeCanceled)
            {
                applicationLifetime.ApplicationStopping.Register(OnAppDisposing);
            }

            _canceledTask.SetCanceled();
        }
Exemple #16
0
        internal static HttpRequestMessage ConvertRequest(HttpContextBase httpContextBase)
        {
            Contract.Assert(httpContextBase != null);

            HttpRequestBase    requestBase = httpContextBase.Request;
            HttpMethod         method      = HttpMethodHelper.GetHttpMethod(requestBase.HttpMethod);
            Uri                uri         = requestBase.Url;
            HttpRequestMessage request     = new HttpRequestMessage(method, uri);

            // Choose a buffered or bufferless input stream based on user's policy
            IHostBufferPolicySelector policySelector = _bufferPolicySelector.Value;
            bool   isInputBuffered = policySelector == null ? true : policySelector.UseBufferedInputStream(httpContextBase);
            Stream inputStream     = isInputBuffered
                                    ? requestBase.InputStream
                                    : httpContextBase.ApplicationInstance.Request.GetBufferlessInputStream();

            request.Content = new StreamContent(inputStream);
            foreach (string headerName in requestBase.Headers)
            {
                string[] values = requestBase.Headers.GetValues(headerName);
                AddHeaderToHttpRequestMessage(request, headerName, values);
            }

            // Add context to enable route lookup later on
            request.Properties.Add(HttpContextBaseKey, httpContextBase);

            // Add the retrieve client certificate delegate to the property bag to enable lookup later on
            request.Properties.Add(HttpPropertyKeys.RetrieveClientCertificateDelegateKey, _retrieveClientCertificate);

            // Add information about whether the request is local or not
            request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy <bool>(() => requestBase.IsLocal));

            // Add information about whether custom errors are enabled for this request or not
            request.Properties.Add(HttpPropertyKeys.IncludeErrorDetailKey, new Lazy <bool>(() => !httpContextBase.IsCustomErrorEnabled));

            return(request);
        }
        private static HttpMessageHandlerOptions CreateOptions(IApplicationBuilder builder, HttpServer server,
                                                               HttpConfiguration configuration, bool bufferRequests)
        {
            Contract.Assert(builder != null);
            Contract.Assert(server != null);
            Contract.Assert(configuration != null);

            ServicesContainer services = configuration.Services;

            Contract.Assert(services != null);

            IHostBufferPolicySelector bufferPolicySelector = services.GetHostBufferPolicySelector()
                                                             ?? new AspNetCoreBufferPolicySelector(bufferRequests);
            IExceptionLogger  exceptionLogger  = ExceptionServices.GetLogger(services);
            IExceptionHandler exceptionHandler = ExceptionServices.GetHandler(services);

            return(new HttpMessageHandlerOptions
            {
                MessageHandler = server,
                BufferPolicySelector = bufferPolicySelector,
                ExceptionLogger = exceptionLogger,
                ExceptionHandler = exceptionHandler,
            });
        }
Exemple #18
0
        public static void DefaultOwinWebApiConfiguration(IAppBuilder app)
        {
            HttpConfiguration configuration =
                new HttpConfiguration(new HttpRouteCollection(HttpRuntime.AppDomainAppVirtualPath));
            Type       traceWriterType     = null;
            var        traceWriterTypeName = NuwaGlobalConfiguration.TraceWriterType;
            MethodInfo httpConfigure       = null;
            var        httpConfigureName   = NuwaGlobalConfiguration.HttpConfigure;

            if (!string.IsNullOrEmpty(traceWriterTypeName))
            {
                var names = traceWriterTypeName.Split(',');
                if (names.Length == 2)
                {
                    var assembly = Assembly.Load(names[1].Trim());
                    traceWriterType = assembly.GetType(names[0].Trim());
                }
                else if (names.Length == 1)
                {
                    traceWriterType = Type.GetType(names[0].Trim());
                }
            }

            if (!string.IsNullOrEmpty(httpConfigureName))
            {
                var names = httpConfigureName.Split(',');
                if (names.Length == 2)
                {
                    var assembly   = Assembly.Load(names[1].Trim());
                    var typeName   = names[0].Substring(0, names[0].LastIndexOf('.')).Trim();
                    var methodName = names[0].Substring(typeName.Length + 1).Trim();
                    var type       = assembly.GetType(typeName);
                    httpConfigure = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public);
                }
                else
                {
                    var typeName   = names[0].Substring(0, names[0].LastIndexOf('.')).Trim();
                    var methodName = names[0].Substring(typeName.Length + 1).Trim();
                    var type       = Type.GetType(typeName);
                    httpConfigure = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public);
                }
            }

            configuration.Routes.MapHttpRoute(
                "api default",
                "api/{controller}/{action}",
                new { action = RouteParameter.Optional });

            if (traceWriterType != null)
            {
                configuration.Services.Replace(typeof(ITraceWriter), Activator.CreateInstance(traceWriterType));
            }

            var httpServer = new HttpServer(configuration);

            configuration.SetHttpServer(httpServer);

            if (httpConfigure != null)
            {
                httpConfigure.Invoke(null, new object[] { configuration });
            }

            IHostBufferPolicySelector bufferPolicySelector = configuration.Services.GetHostBufferPolicySelector() ?? new OwinBufferPolicySelector();

            app.Use(typeof(HttpMessageHandlerAdapter), httpServer, bufferPolicySelector);
        }
        public static IAppBuilder UseWebApi(this IAppBuilder builder, HttpConfiguration configuration, HttpMessageHandler dispatcher)
        {
            IHostBufferPolicySelector bufferPolicySelector = configuration.Services.GetHostBufferPolicySelector() ?? _defaultBufferPolicySelector;

            return(builder.Use(typeof(HttpMessageHandlerAdapter), new HttpServer(configuration, dispatcher), bufferPolicySelector));
        }
 public HttpMessageHandlerAdapterModified(OwinMiddleware next,
                                          HttpMessageHandler messageHandler,
                                          IHostBufferPolicySelector bufferPolicySelector)
     : this(next, messageHandler, bufferPolicySelector, DefaultCallNextPolicy)
 {
 }
 private static HttpMessageHandlerOptions CreateValidOptions(HttpMessageHandler messageHandler,
     IHostBufferPolicySelector bufferPolicySelector)
 {
     return new HttpMessageHandlerOptions
     {
         MessageHandler = messageHandler,
         BufferPolicySelector = bufferPolicySelector,
         ExceptionLogger = new EmptyExceptionLogger(),
         ExceptionHandler = new DefaultExceptionHandler()
     };
 }
        internal static HttpRequestMessage ConvertRequest(HttpContextBase httpContextBase, IHostBufferPolicySelector policySelector)
        {
            Contract.Assert(httpContextBase != null);

            HttpRequestBase requestBase = httpContextBase.Request;
            HttpMethod method = HttpMethodHelper.GetHttpMethod(requestBase.HttpMethod);
            Uri uri = requestBase.Url;
            HttpRequestMessage request = new HttpRequestMessage(method, uri);

            // Choose a buffered or bufferless input stream based on user's policy
            bool bufferInput = policySelector == null ? true : policySelector.UseBufferedInputStream(httpContextBase);
            request.Content = GetStreamContent(requestBase, bufferInput);

            foreach (string headerName in requestBase.Headers)
            {
                string[] values = requestBase.Headers.GetValues(headerName);
                AddHeaderToHttpRequestMessage(request, headerName, values);
            }

            // Add context to enable route lookup later on
            request.SetHttpContext(httpContextBase);

            HttpRequestContext requestContext = new WebHostHttpRequestContext(httpContextBase, requestBase, request);
            request.SetRequestContext(requestContext);

            IDictionary httpContextItems = httpContextBase.Items;

            // Add the OWIN environment, when available (such as when using the OWIN integrated pipeline HTTP module).
            if (httpContextItems != null && httpContextItems.Contains(OwinEnvironmentHttpContextKey))
            {
                request.Properties.Add(OwinEnvironmentKey, httpContextItems[OwinEnvironmentHttpContextKey]);
            }

            // The following three properties are set for backwards compatibility only. The request context controls
            // the behavior for all cases except when accessing the property directly by key.

            // Add the retrieve client certificate delegate to the property bag to enable lookup later on
            request.Properties.Add(HttpPropertyKeys.RetrieveClientCertificateDelegateKey, _retrieveClientCertificate);

            // Add information about whether the request is local or not
            request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy<bool>(() => requestBase.IsLocal));

            // Add information about whether custom errors are enabled for this request or not
            request.Properties.Add(HttpPropertyKeys.IncludeErrorDetailKey, new Lazy<bool>(() => !httpContextBase.IsCustomErrorEnabled));

            return request;
        }
 public HttpMessageHandlerAdapter(OwinMiddleware next, HttpMessageHandler messageHandler,
     IHostBufferPolicySelector bufferPolicySelector)
     : this(next, CreateOptions(messageHandler, bufferPolicySelector))
 {
 }
        // Provides HttpMessageHandlerOptions for callers using the old constructor.
        private static HttpMessageHandlerOptions CreateOptions(HttpMessageHandler messageHandler,
            IHostBufferPolicySelector bufferPolicySelector)
        {
            if (messageHandler == null)
            {
                throw new ArgumentNullException("messageHandler");
            }

            if (bufferPolicySelector == null)
            {
                throw new ArgumentNullException("bufferPolicySelector");
            }

            // Callers using the old constructor get the default exception handler, no exception logging support, and no
            // app cleanup support.

            return new HttpMessageHandlerOptions
            {
                MessageHandler = messageHandler,
                BufferPolicySelector = bufferPolicySelector,
                ExceptionLogger = new EmptyExceptionLogger(),
                ExceptionHandler = new DefaultExceptionHandler(),
                AppDisposing = CancellationToken.None
            };
        }