public static void Register(HttpConfiguration config) { DelegatingHandler[] handlers = new DelegatingHandler[] { new ApiKeyHandler(new OktaProvider()) }; var routeHandlers = HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(config), handlers); // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "Login", routeTemplate: "api/Auth/{action}/{data}", defaults: new { Controller = "Auth", data = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "Index", routeTemplate: "api/index", defaults: new { Controller = "Index" } ); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", handler: routeHandlers, constraints: null, defaults: new { id = RouteParameter.Optional } ); }
public ClientContext(string userName, string password, string serviceUri, IEnumerable <DelegatingHandler> handlers = null) { omniSession = new OmniSession(); piiUser = new User(); if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(serviceUri)) { throw new ArgumentNullException("username, password or service uri"); } HttpMessageHandler innerHandler = null; var apiErrorHandler = new XOMNIPublicApiErrorHandler(); if (handlers != null) { var unifiedHandlers = handlers.ToList(); unifiedHandlers.Insert(0, apiErrorHandler); innerHandler = HttpClientFactory.CreatePipeline(new HttpClientHandler(), unifiedHandlers); } else { innerHandler = HttpClientFactory.CreatePipeline(new HttpClientHandler(), new[] { apiErrorHandler }); } this.UserName = userName; this.Password = password; this.Clients = new ConcurrentDictionary <Type, object>(); this.HttpClient = new HttpClient(innerHandler); this.HttpClient.BaseAddress = new Uri(serviceUri); this.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(AuthenticationSchema, Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", userName, password)))); this.HttpClient.DefaultRequestHeaders.Accept.ParseAdd(string.Format("application/vnd.xomni.api-{0}", "v3_0")); }
public static void Register(HttpConfiguration config) { // Configuración y servicios de API web var cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors); // Rutas de API web config.MapHttpAttributeRoutes(); // List of delegating handlers. DelegatingHandler[] handlers = new DelegatingHandler[] { new AuthorizationHandler() }; // Create a message handler chain with an end-point. var routeHandlers = HttpClientFactory.CreatePipeline( new HttpControllerDispatcher(config), handlers); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: null, handler: routeHandlers ); }
protected void Application_Start(object sender, EventArgs e) { HttpConfiguration config = GlobalConfiguration.Configuration; HttpMessageHandler serverPipeline = HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(config), new[] { new AuthMessageHandler() }); config.Routes.MapHttpRoute( "ServerHttpRoute", "api/cars/{id}", defaults: new { id = RouteParameter.Optional, controller = "cars" }, constraints: null, handler: serverPipeline ); config.Routes.MapHttpRoute( "ClientHttpRoute", "client/cars/{id}", new { id = RouteParameter.Optional, controller = "carsclient" } ); RegisterDependencies(config); // Any complex type parameter which is Assignable From // IRequestCommand will be bound from the URI config.ParameterBindingRules.Insert(0, descriptor => typeof(IRequestCommand).IsAssignableFrom(descriptor.ParameterType) ? new FromUriAttribute().GetBinding(descriptor) : null); }
public void A_message_handler_can_be_specified_to_perform_authentication_prior_to_the_sensor_authorization_check() { var authenticator = new Authenticator { Send = request => { var response = request.CreateResponse(HttpStatusCode.OK); response.Headers.Add("authenticated", "true"); return(response); } }; var httpConfig = new HttpConfiguration(); HttpMessageHandler handler = HttpClientFactory.CreatePipeline( new HttpControllerDispatcher(httpConfig), new[] { authenticator }); httpConfig.MapSensorRoutes( ctx => ctx.Response.Headers.Contains("authenticated") && ctx.Response.Headers.GetValues("authenticated").Single() == "true", handler: handler); var apiClient = new HttpClient(new HttpServer(httpConfig)); apiClient.GetAsync("http://blammo.biz/sensors").Result.StatusCode.Should().Be(HttpStatusCode.OK); }
public void Configuration(IAppBuilder app) { var config = new HttpConfiguration(); config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(name: "routemy", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, handler: new SpecialDelegatingHandler(), constraints: null); config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); //config.MessageHandlers.Add(new SpecialDelegatingHandler()); var pipeline = HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(config), new List <DelegatingHandler>() { new SpecialDelegatingHandler() }); config.Routes.MapHttpRoute(name: "specialroute", routeTemplate: "api2/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: null, handler: pipeline); config.Filters.Add(new MyAuthenticationFilter()); app.UseWebApi(config); }
public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.MessageHandlers.Add(new JWTValidationHandler()); // List of delegating handlers. DelegatingHandler[] handlers = new DelegatingHandler[] { //new MessageHandler3() }; // Create a message handler chain with an end-point. var routeHandlers = HttpClientFactory.CreatePipeline( new HttpControllerDispatcher(config), handlers); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "DefaultApi2", routeTemplate: "api2/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: null, handler: new JWTValidationHandler() ); }
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapHttpRoute( name: "Auth", routeTemplate: "api/auth/verify", defaults: new { controller = "Auth" }); routes.MapHttpRoute( name: "ProxyHandler", routeTemplate: "api/{*path}", handler: HttpClientFactory.CreatePipeline ( innerHandler: new HttpClientHandler(), handlers: new DelegatingHandler[] { new MML.Web.LoanCenter.Handlers.ProxyHandler() } ), defaults: new { path = RouteParameter.Optional }, constraints: null); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); if (_serviceBrokerInitialized == false) { XmlNode serviceConfiguration = ConfigurationManager.GetSection("ServiceConfiguration") as XmlNode; ServiceBroker.RegisterClients(serviceConfiguration); _serviceBrokerInitialized = true; } }
public static void Register(HttpConfiguration config) { var Handler = HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(config), new DelegatingHandler[] { new CustomMessageHandler() }); //config.MessageHandlers.Add(new CustomMessageHandler()); //Global level handler mapping config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "HomeApi", routeTemplate: "Home/{action}/{id}", defaults: new { Controller = "Home", id = RouteParameter.Optional }, constraints: null, handler: Handler //Route level message handler ); }
public static void Register(HttpConfiguration config) { // Web API routes config.MapHttpAttributeRoutes(); // Enables cors in entire application config.EnableCors(); // Creates routing for the application config.Routes.MapHttpRoute( name: "SsoApi", routeTemplate: "v1/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: new { controller = "Sso" }, handler: HttpClientFactory.CreatePipeline( new HttpControllerDispatcher(config), new DelegatingHandler[] { new SsoAuthenticateHandler() }) ); // Creates routing for the application config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "v1/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: null, handler: HttpClientFactory.CreatePipeline( new HttpControllerDispatcher(config), new DelegatingHandler[] { new AuthenticateHandler() }) ); }
public static void Register(HttpConfiguration config) { // Web API configuration and services // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute(name: "Proxy", routeTemplate: "{ *path}", handler: HttpClientFactory.CreatePipeline ( innerHandler: new HttpClientHandler(), // will never get here if proxy is doing its job handlers: new DelegatingHandler[] { new ProxyHandler() } ), defaults: new { path = RouteParameter.Optional }, constraints: null ); }
/// <seealso href="https://developer.foursquare.com/overview/auth#userless" /> public FoursquareUserlessContext(HttpMessageHandler handler, UserlessAccessSettings settings) { if (handler == null) { throw new ArgumentNullException(nameof(handler)); } if (settings == null) { throw new ArgumentNullException(nameof(settings)); } var userlessHandler = HttpClientFactory.CreatePipeline(handler, new DelegatingHandler[] { new QueryAppenderHandler("client_id", settings.ClientId), new QueryAppenderHandler("client_secret", settings.ClientSecret) }); _httpClient = new HttpClient(userlessHandler, false) { BaseAddress = new Uri(Constants.FoursquareApiBaseUrl) }; Categories = new CategoriesClient(_httpClient); Venues = new VenuesClient(_httpClient); Photos = new PhotosClient(_httpClient); }
public static void Configure(HttpConfiguration config) { var pipeline = HttpClientFactory.CreatePipeline( new HttpControllerDispatcher(config), new DelegatingHandler[] { new CompressionHandler(), new NotAcceptablePayloadHandler(), new HtmlResourceRedirectHandler() }); var constraints = new { name = new EndpointConstraint() }; config.Routes.MapHttpRoute("Index", string.Empty, new { controller = "Help" }); config.Routes.MapHttpRoute("WithExtension", "{name}.{ext}", new { controller = "FixedQuery" }, constraints, pipeline); config.Routes.MapHttpRoute("WithoutExtension", "{name}", new { controller = "FixedQuery", ext = string.Empty }, constraints, pipeline); config.Routes.MapHttpRoute("BadRequest", "{*any}", new { controller = "BadRequest" }); config.Services.Add(typeof(IExceptionLogger), new AIExceptionLogger()); config.Formatters.Clear(); config.Formatters.Add(new HttpErrorJsonFormatter()); config.Formatters.Add(new HttpErrorXmlFormatter()); }
public static void Register(HttpConfiguration config) { // Web API configuration and services /*******************************************************/ DelegatingHandler[] handlers = new DelegatingHandler[] { new PerRouteMessageHandler() }; var routeHandlers = HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(config), handlers); /*******************************************************/ // Web API routes config.MapHttpAttributeRoutes(); config.MessageHandlers.Add(new AllRouteMessageHandler()); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "Route2", routeTemplate: "api2/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: null, handler: routeHandlers//<<<<<<<<<<<*********************************** ); }
public static void Register(HttpConfiguration config) { //var cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(); config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "SteamRoute", routeTemplate: "api/steam", defaults: null, constraints: null, handler: HttpClientFactory.CreatePipeline( new HttpControllerDispatcher(config), new DelegatingHandler[] { new SteamHandler() } ) ); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); //config.MessageHandlers.Add(new SteamHandler()); }
public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); // New Code ODataModelBuilder builder = new ODataConventionModelBuilder(); builder.EntitySet <Customer>("Customer"); builder.EntitySet <Job>("Job"); builder.EntitySet <Manager>("Manager"); builder.EntitySet <Technician>("Technician"); builder.EntitySet <DailyStatistic>("DailyStatistic"); config.MapODataServiceRoute( routeName: "ODataRoute", routePrefix: null, model: builder.GetEdmModel(), defaultHandler: HttpClientFactory.CreatePipeline(innerHandler: new HttpControllerDispatcher(config), handlers: new[] { new ODataNullValueMessageHandler() }) ); //Enable $select, $expand, and others config.Count().Filter().OrderBy().Expand().Select().MaxTop(null); }
/// <summary> /// 此扩展方法,用于调用引用的dll,使用其中的route /// </summary> /// <param name="httpConfiguration"></param> public static void RegisterAssembly(this HttpConfiguration httpConfiguration) { IEnumerable <Assembly> assemblies = BuildManager.GetReferencedAssemblies().Cast <Assembly>().Where(x => x.GetName().Name.StartsWith("BLL")); foreach (Assembly assembly in assemblies) { //查找拥有特定特性路由的控制器类 List <Type> types = assembly.GetTypes().Where(x => x.IsDefined(typeof(RegRouteHandlerAttribute))).ToList(); foreach (Type type in types) { //获取特性路由对象 RegRouteHandlerAttribute attribute = type.GetCustomAttribute <RegRouteHandlerAttribute>(); //创建handler对象 DelegatingHandler handler = Activator.CreateInstance(type) as DelegatingHandler; //创建自定义消息管道 HttpMessageHandler httpHandlers = HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(httpConfiguration), new DelegatingHandler[] { handler }); //注册路由 httpConfiguration.Routes.MapHttpRoute( name: attribute.ControllerName, routeTemplate: attribute.Template, defaults: new { controller = attribute.ControllerName }, constraints: null, handler: httpHandlers ); } } }
public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); var cacheService = new MemoryCacheService(int.Parse(ConfigurationManager.AppSettings["CacheDurationInSeconds"])); var configuration = new CachedConfiguration(new ConfigurationManagerConfiguration(), cacheService); var webProxyUserRepository = new CachedWebProxyUserRepository(new SqlServerWebProxyUserRepository(configuration), cacheService); //var proxyLogging = new FileProxyLogging(configuration); var proxyLogging = new AzureBlobStorageLogging(configuration); //var proxyLogging = new NullProxyLogging(); //var proxyRouting = new LogicRouting(); var proxyRouting = new NasAvWebServicesRouting(configuration, webProxyUserRepository); config.Routes.MapHttpRoute(name: "Proxy", routeTemplate: "{*path}", handler: HttpClientFactory.CreatePipeline( innerHandler: new HttpClientHandler(), // will never get here if proxy is doing its job handlers: new DelegatingHandler[] { new ProxyHandler(proxyRouting, proxyLogging, configuration) }), defaults: new { path = RouteParameter.Optional }, constraints: null ); }
private static HttpMessageHandler GetSecureHandler(HttpConfiguration config) { DelegatingHandler[] handlers = new DelegatingHandler[] { new BasicAuthenticationHandler() }; return(HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(config), handlers)); }
/// <seealso href="https://developer.foursquare.com/overview/versioning" /> private static HttpMessageHandler CreateHandler() { return(HttpClientFactory.CreatePipeline(new HttpClientHandler(), new DelegatingHandler[] { new OAuthTokenSwitchHandler(), new QueryAppenderHandler("v", "20170523") })); }
/// <summary> /// Prepares the server for operation. /// </summary> /// <remarks> /// This method must be called after all configuration is complete /// but before the first request is processed. /// </remarks> protected virtual void Initialize() { // Do final initialization of the configuration. // It is considered immutable from this point forward. _configuration.EnsureInitialized(); // Create pipeline InnerHandler = HttpClientFactory.CreatePipeline(_dispatcher, _configuration.MessageHandlers); }
protected override void UpdateConfiguration(WebRouteConfiguration configuration) { configuration. MapODataServiceRoute( routeName: "RawValue", routePrefix: "RawValue", model: GetEdmModel(configuration), pathHandler: new DefaultODataPathHandler(), routingConventions: ODataRoutingConventions.CreateDefault(), defaultHandler: HttpClientFactory.CreatePipeline(innerHandler: new HttpControllerDispatcher(configuration), handlers: new[] { new ODataNullValueMessageHandler() })); }
// Web API configuration and services public static void Register(HttpConfiguration config) { // Enable CORS with default pipeline config.EnableCors(); // Setting up JSON serialization config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); config.Formatters.JsonFormatter.MediaTypeMappings.Add(new RequestHeaderMapping( "Accept", "text/html", StringComparison.InvariantCultureIgnoreCase, true, "application/json")); // Web API routes config.MapHttpAttributeRoutes(); // Default Route to index.html config.Routes.MapHttpRoute( name: "Index", routeTemplate: "{id}.html", defaults: new { id = "index" }); // If we want a global access token delegating handler do it here // Global DelegatingHandler config.MessageHandlers.Add(new AccessTokenAuthenticationDelegatingHandler()); // Non-default Controller Routes config.Routes.MapHttpRoute( name: "Sso", routeTemplate: "{version}/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: new { version = "v1", controller = "Sso" }, handler: HttpClientFactory.CreatePipeline( new HttpControllerDispatcher(config), new DelegatingHandler[] { new SsoAccessTokenAuthenticationDelegatingHandler() }) ); // Default Controller Route config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "{version}/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional, action = "Get" }, constraints: new { version = "v1" } ); // Global Authorization Filters // Global Action Filters // Global Exception Filters config.Filters.Add(new AnyExceptionFilterAttribute()); }
public static void UpdateConfiguration(HttpConfiguration configuration) { configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; configuration. MapODataServiceRoute( routeName: "RawValue", routePrefix: "RawValue", model: GetEdmModel(configuration), pathHandler: new DefaultODataPathHandler(), routingConventions: ODataRoutingConventions.CreateDefault(), defaultHandler: HttpClientFactory.CreatePipeline(innerHandler: new HttpControllerDispatcher(configuration), handlers: new[] { new ODataNullValueMessageHandler() })); }
private static void MapRoute(HttpConfiguration httpConfiguration, IEdmModel edmModel, string routePrefix, HttpBatchHandler batchHandler) { // batch handler should be mapped first var routeTemplate = string.IsNullOrEmpty(routePrefix) ? ODataRouteConstants.Batch : routePrefix + '/' + ODataRouteConstants.Batch; httpConfiguration.Routes.MapHttpBatchRoute(routePrefix + "Batch", routeTemplate, batchHandler); var httpMessageHandler = HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(httpConfiguration), new DelegatingHandler[0]); httpConfiguration.MapODataServiceRoute(routePrefix, routePrefix, edmModel, httpMessageHandler); }
public static void Register(HttpConfiguration config) { // Web API configuration and services config.Services.Replace(typeof(IExceptionHandler), new AppExceptionHandler()); config.Services.Replace(typeof(IExceptionLogger), new AppExceptionLogger()); // Web API routes // Support for More Media Types var bson = new BsonMediaTypeFormatter(); bson.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.contoso")); config.Formatters.Add(bson); // DelegatingHandler[] handlers = new DelegatingHandler[]{new TokenAuthenicationHandler()}; // Create a message handler chain with an end-point. // var routeHandlers = HttpClientFactory.CreatePipeline(new HttpControllerDispatcher(config), handlers); config.MapHttpAttributeRoutes(); //config.Routes.MapHttpRoute( // name: "DefaultPublicApi", // routeTemplate: "apiV2/public/{id}", // defaults: new { controller = "MyKeyController", Id = RouteParameter.Optional } // ); config.Routes.MapHttpRoute( name: "ApiRoot", routeTemplate: "api/public/{method}", defaults: new { controller = "MyKeyController", method = "ApiKey" } ); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }, constraints: null, handler: HttpClientFactory.CreatePipeline( new HttpControllerDispatcher(config), new DelegatingHandler[] { new TokenAuthenicationHandler() }) // handler: new TokenAuthenicationHandler(GlobalConfiguration.Configuration) ); // config.MessageHandlers.Add(new TokenAuthenicationHandler()); }
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); // Pipelines HttpMessageHandler siteLanguagePipeline = HttpClientFactory.CreatePipeline( new HttpControllerDispatcher(GlobalConfiguration.Configuration), new[] { new SiteLanguageDispatcher() }); HttpMessageHandler cityPipeline = HttpClientFactory.CreatePipeline( new HttpControllerDispatcher(GlobalConfiguration.Configuration), new DelegatingHandler[] { new SiteLanguageDispatcher(), new CityDispatcher() }); HttpMessageHandler hotelPipeline = HttpClientFactory.CreatePipeline( new HttpControllerDispatcher(GlobalConfiguration.Configuration), new DelegatingHandler[] { new SiteLanguageDispatcher(), new CityDispatcher(), new HotelDispatcher() }); routes.MapHttpRoute( name: "CityApiRoute", routeTemplate: "content/{site}/{language}/cities/{cityName}", defaults: new { controller = "City", cityName = RouteParameter.Optional }, constraints: null, handler: siteLanguagePipeline ); routes.MapHttpRoute( name: "HotelApiRoute", routeTemplate: "content/{site}/{language}/cities/{cityName}/hotels/{id}", defaults: new { controller = "Hotel", id = RouteParameter.Optional }, constraints: null, handler: cityPipeline ); routes.MapHttpRoute( name: "SpaApiRoute", routeTemplate: "content/{site}/{language}/cities/{cityName}/hotels/{hotelName}/spas/{id}", defaults: new { controller = "Spa", id = RouteParameter.Optional }, constraints: null, handler: hotelPipeline ); routes.MapHttpRoute( name: "SpaApiRoute1", routeTemplate: "content/{site}/{language}/cities/{cityName}/spas/{id}", defaults: new { controller = "Spa", id = RouteParameter.Optional }, constraints: null, handler: cityPipeline ); }
/// <summary> /// Gets a custom message handler that explicitly contains the CorsMessageHandler for use /// with our RestApi routes. /// </summary> /// <param name="config"></param> /// <returns></returns> private static HttpMessageHandler GetMessageHandler(HttpConfiguration config) { // Create a message handler chain with an end-point. return(HttpClientFactory.CreatePipeline( new HttpControllerDispatcher(config), new DelegatingHandler[] { //Explicitly include the CorsMessage handler! // we're doing this so people don't have to do EnableCors() in their startup, // we don't care about that, we always want to support Cors for the rest api new CorsMessageHandler(config) })); }
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(); }
SomeFunction() { using (var client = new HttpClient( HttpClientFactory.CreatePipeline( new HttpClientHandler { CookieContainer = new CookieContainer(), UseCookies = true }, new DelegatingHandler[] { new CustomHandler() }))) { //do something with `client` } }