Inheritance: HttpMessageHandler
        public MusicStoreBootStrap ConfigureRoute()
        {
            // List of delegating handlers.
            DelegatingHandler[] handlers = new DelegatingHandler[] { new AdminAuthorizationMessageHandler(new AdminUserQuery()) };

            // Create a message handler chain with an end-point.
            var routeHandlers = HttpClientFactory.CreatePipeline(
                new HttpControllerDispatcher(httpConfiguration), handlers);
            httpConfiguration.Routes.MapHttpRoute(
                name: "AdminRoutes",
                routeTemplate: "api/AdminUser/{user}",
                defaults: new { controller = "AdminUser", user = RouteParameter.Optional }
                , constraints: null
                , handler: routeHandlers);

            httpConfiguration.Routes.MapHttpRoute(
              name: "Inventory",
              routeTemplate: "api/Inventory/{id}",
              defaults: new { controller = "Inventory", id = RouteParameter.Optional }
              , constraints: null
              , handler: routeHandlers);

            httpConfiguration.Routes.MapHttpRoute(
             name: "ActionApi",
             routeTemplate: "api/{controller}/{action}/{id}",
             defaults: new { controller = "Product", id = RouteParameter.Optional });

            httpConfiguration.Routes.MapHttpRoute(
             name: "DefaultApi",
             routeTemplate: "api/{controller}/{id}",
             defaults: new { controller = "Product", id = RouteParameter.Optional });
            httpConfiguration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            return this;
        }
 public DelegatingHandler CreateHandler(HttpConfiguration httpConfig, DelegatingHandler innerHandler = null)
 {
     return new CorsMessageHandler(this, httpConfig)
     {
         InnerHandler = innerHandler
     };
 }
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            config.MessageHandlers.Add(new CustomHeaderHandler());

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            var handlers = new DelegatingHandler[]
            {
                new PreRouteMessageHandler()
            };
            var routeHandlers = HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(config), handlers);
            config.Routes.MapHttpRoute(
                name: "Route2",
                routeTemplate: "api1/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional },
                constraints: null,
                handler: routeHandlers
            );
            config.MessageHandlers.Add(new MethodOverrideHandler());
        }
        internal async Task<dynamic> PostForm(
            IEnumerable<KeyValuePair<string, string>> formParameters,
            string path, DelegatingHandler[] handlers, IEnumerable<KeyValuePair<string, string>> headerParameters = null, bool shouldRetry = true)
        {
            using (var client = HttpClientFactory.Create(handlers == null
                        ? new DelegatingHandler[] { new UserAgentHandler() }
                        : handlers.ToArray()))
            {
                var uri = _baseAddress + path;
                var httpResponse =
                    await client.PostAsync(uri, new FormUrlEncodedContent(formParameters));

                try
                {
                    return await HandleResponse(httpResponse);
                }
                catch (UnauthorizedException)
                {
                    if (shouldRetry)
                    {
                        _credentials.ResetAccessToken();
                        using (var retryClient = HttpClientFactory.Create(await GetHandlers(headerParameters)))
                        {
                            httpResponse = await retryClient.PostAsync(uri, new FormUrlEncodedContent(formParameters));
                            return await HandleResponse(httpResponse);
                        } 
                    }
                    throw;
                }
            }
        }
Beispiel #5
0
        private void CreateEncryptedRoute(HttpConfiguration configuration)
        {
            var section = (NameValueCollection)ConfigurationManager.GetSection("Api2CryptoGraphySettings");
            if (section == null)
            {
                throw new ApplicationException("Config section 'RestfulWebService' has not been set.");
            }

            // arrange.
            var settings = new CryptoGraphySettings(section);
            var cryptoHandler = new ServerCryptoHandler(settings.SecretKey, settings.InitialVector, settings.HashKey);
            var injection = new DelegatingHandler[] { new ServerMessageDumper(), cryptoHandler }; // dump decrypted request & plain response.
            var handler = HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(configuration), injection);

            // register encrypted HTTP route.
            configuration.Routes.MapHttpRoute("Encrypted Route", "api2/{controller}/{action}", null, null, handler);

            // register timestamp as a route.
            var timestampProvider = new DefaultTimestampProvider(TimeSpan.FromMinutes(15)) as ITimestampProvider<string>;
            var timestampHandler = new HttpTimestampHandler<string>(timestampProvider);
            configuration.Routes.MapHttpRoute("Timestamp Route", "api3/!timestamp!/get", null, null, timestampHandler);

            // register global timestamp service, it should align with encrypted HTTP route or will not work.
            configuration.MessageHandlers.Add(new HttpTimestampHandler<string>(configuration, "api2/!timestamp!/get", timestampProvider));
        }
        public MessageHandlerTracer(DelegatingHandler innerHandler, ITraceWriter traceWriter)
        {
            Contract.Assert(innerHandler != null);
            Contract.Assert(traceWriter != null);

            _innerHandler = innerHandler;
            _traceWriter = traceWriter;
        }
Beispiel #7
0
 private IEnumerable<string> GetChains(DelegatingHandler handler)
 {
     yield return handler.GetType().FullName;
     var innerHander = handler.InnerHandler as DelegatingHandler;
     if (innerHander != null)
     {
         yield return innerHander.GetType().FullName;
     }
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="RetryDelegatingHandler"/> class. 
 /// </summary>
 /// <param name="retryPolicy">Retry policy to use.</param>
 /// <param name="innerHandler">Inner http handler.</param>
 public RetryDelegatingHandler(RetryPolicy retryPolicy, DelegatingHandler innerHandler)
     : base(innerHandler)
 {
     if (retryPolicy == null)
     {
         throw new ArgumentNullException("retryPolicy");
     }
     RetryPolicy = retryPolicy;
 }
        protected override BatchServiceClient CreateBatchRestClient(string url, string accountName, string key, DelegatingHandler handler = default(DelegatingHandler))
        {
            // Add HTTP recorder to the BatchRestClient
            HttpMockServer mockServer = HttpMockServer.CreateInstance();
            mockServer.InnerHandler = new HttpClientHandler();

            BatchServiceClient restClient = base.CreateBatchRestClient(url, accountName, key, mockServer);

            return restClient;
        }
        private void RegisterEncryptedRoute(HttpConfiguration configuration, ITimestampProvider<string> timestampProvider)
        {
            // arrange.
            var cryptoHandler = new ServerCryptoHandler("secretKeyPassword", "initialVectorPassword", "hashKeyString", timestampProvider);
            var injection = new DelegatingHandler[] { new ServerMessageDumper(), cryptoHandler, new ServerMessageDumper() };
            var handler = HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(configuration), injection);

            // register encrypted HTTP route.
            configuration.Routes.MapHttpRoute("Encrypted API", "api2/{controller}/{action}", null, null, handler);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="RetryDelegatingHandler"/> class. Sets 
 /// the default retry policty base on Exponential Backoff.
 /// </summary>
 /// <param name="innerHandler">Inner http handler.</param>
 public RetryDelegatingHandler(DelegatingHandler innerHandler)
     : base(innerHandler)
 {
     var retryStrategy = new ExponentialBackoffRetryStrategy(
         DefaultNumberOfAttempts,
         DefaultMinBackoff,
         DefaultMaxBackoff,
         DefaultBackoffDelta);
     RetryPolicy = new RetryPolicy<HttpStatusCodeErrorDetectionStrategy>(retryStrategy);
 }
            public HttpResponseMessage ExecuteRequest(DelegatingHandler testTarget, HttpRequestMessage requestMessage)
            {
                testTarget.InnerHandler = new OKHandler();
                InnerHandler = testTarget;

                var requestTask = SendAsync(requestMessage, new CancellationToken());

                requestTask.Wait(5000); // 5 second timeout - tests should be quicker than this, but better than infinite for now

                return requestTask.Result;
            }
        public BasicAuthenticationHandler(DelegatingHandler innerChannel, IUserValidation userValidation, string realm)
            : base(innerChannel)
        {
            if (userValidation == null)
                throw new ArgumentNullException("userValidation");

            if (string.IsNullOrEmpty(realm))
                throw new ArgumentNullException("realm");

            this.userValidation = userValidation;
            this.realm = realm;
        }
            public HttpResponseMessage ExecuteRequest(DelegatingHandler testTarget, HttpRequestMessage requestMessage)
            {
                testTarget.InnerHandler = new OKHandler();
                InnerHandler = testTarget;

                var requestTask = SendAsync(requestMessage, new CancellationToken());

                while (!requestTask.IsCompleted)
                {
                }

                return requestTask.Result;
            }
 /// <summary>
 /// 获得MyHttpServer牵头的HttpMessageHandler链
 /// </summary>
 /// <param name="handler"></param>
 /// <returns></returns>
 private IEnumerable<string> GetHandlerChain(DelegatingHandler handler)
 {
     yield return handler.GetType().Name;
     while (null != handler.InnerHandler)
     {
         yield return handler.InnerHandler.GetType().Name;
         handler = handler.InnerHandler as DelegatingHandler;
         if (null == handler)
         {
             break;
         }
     }
 }
Beispiel #16
0
        static void Main(string[] args)
        {

            var baseAddress = "http://localhost:8080";
            HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(baseAddress);
           // config.MessageHandlers.Add(new ProgressMessageHandler() { });


            // Web API 路由
            config.MapHttpAttributeRoutes();

            //全局允许CROS
            // config.EnableCors();//启用跨域


            config.Routes.MapHttpRoute
           (
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
            );
            config.MaxConcurrentRequests = 1000;
            var handlers = new DelegatingHandler[] { new PassiveAuthenticationMessageHandler(), new HttpServer() };
            var routeHandlers = HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(config), handlers);
            config.Routes.MapHttpRoute(
                   name: "CustomerRouter",
                  routeTemplate: "MyAPI/{Controller}/{Action}/Id",
                  defaults: new { Id = RouteParameter.Optional },
                  constraints: null,
                  handler: routeHandlers
                );
            HttpSelfHostServer server = new HttpSelfHostServer(config);
            server.OpenAsync();


            TaskManager.Instance.Initialize();
            TaskManager.Instance.Start();
           DefaultHttpBatchHandler batchHandler = new DefaultHttpBatchHandler(server);

            Console.WriteLine("Server  http://localhost:8080   Open now ....at {0}..", server.Configuration.VirtualPathRoot);
            config.EnsureInitialized();
            foreach (var route in config.Routes)
            {
                System.Diagnostics.Debug.WriteLine(route);
            }

            Console.ReadLine();

        }
        internal HttpServerWrapper(string baseAddress)
        {
            var configuration = new HttpSelfHostConfiguration(baseAddress);

            // arrange.
            var injection = new DelegatingHandler[] { new ServerMessageDumper() };
            var handler = HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(configuration), injection);

            // register HTTP route.
            configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{action}", null, null, handler);

            // startup local HTTP server.
            this.inner = new HttpSelfHostServer(configuration);
            this.inner.OpenAsync().Wait();

            this.configuration = configuration;
        }
Beispiel #18
0
        public void SuppressHostPrincipal_InsertsSuppressHostPrincipalMessageHandler()
        {
            // Arrange
            DelegatingHandler existingHandler = new Mock <DelegatingHandler>(MockBehavior.Strict).Object;

            using (HttpConfiguration configuration = new HttpConfiguration())
            {
                configuration.MessageHandlers.Add(existingHandler);

                // Act
                configuration.SuppressHostPrincipal();

                // Assert
                Assert.Equal(2, configuration.MessageHandlers.Count);
                DelegatingHandler firstHandler = configuration.MessageHandlers[0];
                Assert.IsType <SuppressHostPrincipalMessageHandler>(firstHandler);
            }
        }
        /// <summary>
        /// Creates an <see cref="HttpClient"/>
        /// </summary>
        /// <param name="primaryHandlers">The handlers that will be added to the top of the chain.</param>
        public virtual HttpClient CreateHttpClient(params DelegatingHandler[] primaryHandlers)
        {
            var delegateHandlers = new DelegatingHandler[]
            {
                new AuthenticationHandler(cloudCredentials: credentials),
                new UserAgentHandler(headerValues: headerValues),
                new TracingHandler(),
                new RetryHandler(),
            };

            var pipeline = (HttpMessageHandler)(new HttpClientHandler());
            var reversedHandlers = primaryHandlers.CoalesceEnumerable().Concat(delegateHandlers).ToArray().Reverse();
            foreach (var handler in reversedHandlers)
            {
                handler.InnerHandler = pipeline;
                pipeline = handler;
            }

            return new HttpClient(pipeline);
        }
        public void CreatePipeline_WiresUpHandlers(int maxHandlerCount)
        {
            // Arrange
            List <DelegatingHandler> handlers = new List <DelegatingHandler>();

            for (int handlerCount = 0; handlerCount < maxHandlerCount; handlerCount++)
            {
                handlers.Add(new MockDelegatingHandler());
            }

            HttpClientHandler innerHandler = new HttpClientHandler();

            // Act
            DelegatingHandler pipeline = HttpClientFactory.CreatePipeline(innerHandler, handlers) as DelegatingHandler;

            // Assert
            for (int index = 0; index < handlers.Count - 1; index++)
            {
                Assert.Same(handlers[index], pipeline);
                pipeline = pipeline.InnerHandler as DelegatingHandler;
            }
            Assert.Same(innerHandler, pipeline.InnerHandler);
        }
        /// <summary>
        /// Creates an instance of an <see cref="HttpMessageHandler"/> using the HTTP message handlers
        /// provided in the constructor.
        /// </summary>
        /// <param name="innerChannel">The inner channel represents the destination of the HTTP message channel.</param>
        /// <returns>The HTTP message channel.</returns>
        protected virtual HttpMessageHandler OnCreate(HttpMessageHandler innerChannel)
        {
            if (innerChannel == null)
            {
                throw FxTrace.Exception.ArgumentNull("innerChannel");
            }

            // Get handlers either by constructing types or by calling Func
            IEnumerable<DelegatingHandler> handlerInstances = null;
            try
            {
                if (_handlerFunc != null)
                {
                    handlerInstances = _handlerFunc.Invoke();
                    if (handlerInstances != null)
                    {
                        foreach (DelegatingHandler handler in handlerInstances)
                        {
                            if (handler == null)
                            {
                                throw FxTrace.Exception.Argument("handlers", SR.Format(SR.DelegatingHandlerArrayFromFuncContainsNullItem, s_delegatingHandlerType.Name, GetFuncDetails(_handlerFunc)));
                            }
                        }
                    }
                }
                else if (_handlerCtors != null)
                {
                    DelegatingHandler[] instances = new DelegatingHandler[_handlerCtors.Length];
                    for (int cnt = 0; cnt < _handlerCtors.Length; cnt++)
                    {
                        instances[cnt] = (DelegatingHandler)_handlerCtors[cnt].Invoke(Array.Empty<Type>());
                    }

                    handlerInstances = instances;
                }
            }
            catch (TargetInvocationException targetInvocationException)
            {
                throw FxTrace.Exception.AsError(targetInvocationException);
            }

            // Wire handlers up
            HttpMessageHandler pipeline = innerChannel;
            if (handlerInstances != null)
            {
                foreach (DelegatingHandler handler in handlerInstances)
                {
                    if (handler.InnerHandler != null)
                    {
                        throw FxTrace.Exception.Argument("handlers", SR.Format(SR.DelegatingHandlerArrayHasNonNullInnerHandler, s_delegatingHandlerType.Name, "InnerHandler", handler.GetType().Name));
                    }

                    handler.InnerHandler = pipeline;
                    pipeline = handler;
                }
            }

            return pipeline;
        }
 /// <summary>
 /// Get an instance of the AlertsClient class that uses the handler while initiating web requests.
 /// </summary>
 /// <param name="handler">the handler</param>
 public override AutoscaleClient WithHandler(DelegatingHandler handler)
 {
     return WithHandler(new AutoscaleClient(), handler);
 }
        protected virtual BatchServiceClient CreateBatchRestClient(string url, string accountName, string key, DelegatingHandler handler = default(DelegatingHandler))
        {
            ServiceClientCredentials credentials = new Microsoft.Azure.Batch.Protocol.BatchSharedKeyCredential(accountName, key);

            BatchServiceClient restClient = handler == null ? new BatchServiceClient(new Uri(url), credentials) : new BatchServiceClient(new Uri(url), credentials, handler);

            restClient.HttpClient.DefaultRequestHeaders.UserAgent.Add(Microsoft.WindowsAzure.Commands.Common.AzurePowerShell.UserAgentValue);

            restClient.SetRetryPolicy(null); //Force there to be no retries
            restClient.HttpClient.Timeout = Timeout.InfiniteTimeSpan; //Client side timeout will be set per-request

            return restClient;
        }
Beispiel #24
0
 public TraceMessageHandler(DelegatingHandler innerChannel)
     : base(innerChannel)
 {
 }
Beispiel #25
0
 public static Task<HttpResponseMessage> InvokeMessageHandler(HttpRequestMessage requestMessage, DelegatingHandler handler, CancellationToken cancellationToken=default(CancellationToken))
 {
     handler.InnerHandler=new DummyHandler();
     var messageInvoker = new HttpMessageInvoker(handler);
     return messageInvoker.SendAsync(requestMessage, cancellationToken);
 }
 public MediaServicesManagementClient WithHandler(DelegatingHandler handler)
 {
     return (MediaServicesManagementClient)WithHandler(new MediaServicesManagementClient(), handler);
 }
 public override ApplicationGatewayManagementClient WithHandler(DelegatingHandler handler)
 {
     return (ApplicationGatewayManagementClient)WithHandler(new ApplicationGatewayManagementClient(), handler);
 }
 private static DelegatingHandler[] AddJwtTokenRefresher(DelegatingHandler[] srcHandlers, MicrosoftAppCredentials credentials)
 {
     var handlers = new List<DelegatingHandler>(srcHandlers);
     handlers.Add(new JwtTokenRefresher(credentials));
     return handlers.ToArray();
 }
 /// <summary>
 /// Generate a Resource Management client from the test base to use for managing resource groups.
 /// </summary>
 /// <returns>Resource Management client</returns>
 public static ResourceManagementClient GetResourceClient(DelegatingHandler handler)
 {
     return TestBase.GetServiceClient<ResourceManagementClient>(new CSMTestEnvironmentFactory()).WithHandler(handler);
 }
 public override BatchManagementClient WithHandler(DelegatingHandler handler)
 {
     return (BatchManagementClient)WithHandler(new BatchManagementClient(), handler);
 }
 public override StorageManagementClient WithHandler(DelegatingHandler handler)
 {
     return (StorageManagementClient)WithHandler(new StorageManagementClient(), handler);
 }
Beispiel #32
-1
        public static async Task<int> HttpInvoke(Uri uri, TokenCacheInfo cacheInfo, string verb, DelegatingHandler handler, HttpContent content)
        {
            using (var client = new HttpClient(handler))
            {
                client.DefaultRequestHeaders.Add("Authorization", cacheInfo.CreateAuthorizationHeader());
                client.DefaultRequestHeaders.Add("User-Agent", Constants.UserAgent.Value);
                client.DefaultRequestHeaders.Add("Accept", Constants.JsonContentType);

                if (Utils.IsRdfe(uri))
                {
                    client.DefaultRequestHeaders.Add("x-ms-version", "2013-10-01");
                }

                client.DefaultRequestHeaders.Add("x-ms-request-id", Guid.NewGuid().ToString());

                HttpResponseMessage response = null;
                if (String.Equals(verb, "get", StringComparison.OrdinalIgnoreCase))
                {
                    response = await client.GetAsync(uri);
                }
                else if (String.Equals(verb, "delete", StringComparison.OrdinalIgnoreCase))
                {
                    response = await client.DeleteAsync(uri);
                }
                else if (String.Equals(verb, "post", StringComparison.OrdinalIgnoreCase))
                {
                    response = await client.PostAsync(uri, content);
                }
                else if (String.Equals(verb, "put", StringComparison.OrdinalIgnoreCase))
                {
                    response = await client.PutAsync(uri, content);
                }
                else if (String.Equals(verb, "patch", StringComparison.OrdinalIgnoreCase))
                {
                    using (var message = new HttpRequestMessage(new HttpMethod("PATCH"), uri))
                    {
                        message.Content = content;
                        response = await client.SendAsync(message).ConfigureAwait(false);
                    }
                }
                else
                {
                    throw new InvalidOperationException(String.Format("Invalid http verb {0}!", verb));
                }

                using (response)
                {
                    if (response.IsSuccessStatusCode)
                    {
                        return 0;
                    }

                    return (-1) * (int)response.StatusCode;
                }
            }
        }