private static bool IsMediaTypeAccepted(HttpRequestMessage request) { var contentNegotiator = new DefaultContentNegotiator(); var formatter = contentNegotiator.Negotiate(typeof(JsonMediaTypeFormatter), request, GlobalConfiguration.Configuration.Formatters); return(formatter != null); }
public void Configuration(IAppBuilder app) { var httpConfiguration = new HttpConfiguration(); httpConfiguration.Formatters.Add(new BsonMediaTypeFormatter()); var defaultNegotiator = new DefaultContentNegotiator(excludeMatchOnTypeOnly: true); httpConfiguration.Services.Replace(typeof(IContentNegotiator), defaultNegotiator); httpConfiguration.MapHttpAttributeRoutes(); app.UseWebApi(httpConfiguration); }
public void Configuration(IAppBuilder appBuilder) { var config = new HttpConfiguration(); var negotiator = new DefaultContentNegotiator(excludeMatchOnTypeOnly: true); config.Services.Replace(typeof(IContentNegotiator), negotiator); config.MapHttpAttributeRoutes(); appBuilder.UseWebApi(config); }
public static void WhenAcceptHeaderValuesHaveQualityThenNegotiatedMediaTypeMatchesHigherQuality(string mediaType1, double quality1, string mediaType2, double quality2, string expected) { var actual = new DefaultContentNegotiator().Negotiate( new[] { "text/xml", "text/json" }, new[] { new MediaTypeWithQualityHeaderValue(mediaType1, quality1), new MediaTypeWithQualityHeaderValue(mediaType2, quality2) }); Assert.AreEqual(expected, actual); }
private static MediaTypeHeaderValue GetContentTypeFromQueryString(IEdmModel model, Type type, string dollarFormat) { IEnumerable <ODataMediaTypeFormatter> formatters = CreateProductUnderTest(model); IEnumerable <ODataMediaTypeFormatter> feedFormatters = formatters.Where(f => f.CanWriteType(type)); IContentNegotiator negotiator = new DefaultContentNegotiator(false); MediaTypeHeaderValue mediaType; using (HttpRequestMessage request = new HttpRequestMessage()) { request.RequestUri = new Uri("http://any/?$format=" + dollarFormat); ContentNegotiationResult result = negotiator.Negotiate(type, request, formatters); mediaType = result.MediaType; } // We don't care what the charset is for these tests. mediaType.Parameters.Remove(mediaType.Parameters.Single(p => p.Name == "charset")); return(mediaType); }
private static MediaTypeHeaderValue GetDefaultContentType(IEdmModel model, Type type) { // Arrange IEnumerable <ODataMediaTypeFormatter> formatters = CreateProductUnderTest(model); IEnumerable <ODataMediaTypeFormatter> feedFormatters = formatters.Where(f => f.CanWriteType(type)); IContentNegotiator negotiator = new DefaultContentNegotiator(false); MediaTypeHeaderValue mediaType; using (HttpRequestMessage request = new HttpRequestMessage()) { // Act ContentNegotiationResult result = negotiator.Negotiate(type, request, formatters); // Collect results for Assert mediaType = result.MediaType; } // We don't care what the charset is for these tests. mediaType.Parameters.Remove(mediaType.Parameters.Single(p => p.Name == "charset")); return(mediaType); }
private static MediaTypeHeaderValue GetContentTypeFromQueryString(IEdmModel model, Type type, string dollarFormat) { var formatters = CreateOutputFormatters(model); var feedFormatters = formatters.Where(f => f.CanWriteType(type)); IContentNegotiator negotiator = new DefaultContentNegotiator(false); MediaTypeHeaderValue mediaType; using (HttpRequestMessage request = new HttpRequestMessage()) { request.RequestUri = string.IsNullOrEmpty(dollarFormat) ? request.RequestUri = new Uri("http://any") : new Uri("http://any/?$format=" + dollarFormat); request.EnableODataDependencyInjectionSupport(model); ContentNegotiationResult result = negotiator.Negotiate(type, request, formatters); mediaType = result.MediaType; } // We don't care what the charset is for these tests. mediaType.Parameters.Remove(mediaType.Parameters.Single(p => p.Name == "charset")); return(mediaType); }
public static void Configuration(IAppBuilder app) { var dbConnectionString = WebConfigurationManager.AppSettings["DbConnectionString"]; app.UseNLog(); var logger = app.GetLoggerFactory().Create("Startup"); var config = new HttpConfiguration(); // Use camel case JSON config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false; // Return Not Acceptable for unknown content types var defaultNegotiator = new DefaultContentNegotiator(excludeMatchOnTypeOnly: true); config.Services.Replace(typeof(IContentNegotiator), defaultNegotiator); // Fluent Validation FluentValidationModelValidatorProvider.Configure(config); // IOC using Autofac var builder = new ContainerBuilder(); builder.RegisterType <DbRepository>().As <IDbRepository>().InstancePerLifetimeScope(); builder.RegisterInstance(new DbRepository.Setting(dbConnectionString)).SingleInstance(); builder.RegisterType <ProductRepository>().As <IProductRepository>().InstancePerLifetimeScope(); builder.RegisterInstance(new ProductRepository.Setting(dbConnectionString)).SingleInstance(); builder.RegisterType <SellerRepository>().As <ISellerRepository>().InstancePerLifetimeScope(); builder.RegisterInstance(new SellerRepository.Setting(dbConnectionString)).SingleInstance(); builder.RegisterType <Mapper>().As <IMapper>().InstancePerLifetimeScope(); builder.RegisterType <TypeHelper>().As <ITypeHelper>().InstancePerLifetimeScope(); builder.RegisterType <PropertyMappingService>().As <IPropertyMappingService>().InstancePerLifetimeScope(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); var container = builder.Build(); config.DependencyResolver = new AutofacWebApiDependencyResolver(container); app.UseAutofacMiddleware(container); app.UseAutofacWebApi(config); // IOC using Autofac // Caching var objCacheCow = new CacheCow.Server.CachingHandler(config); config.MessageHandlers.Add(objCacheCow); // Rate Limiting. Does not return response headers like X-Rate-Limit. config.MessageHandlers.Add(new ThrottlingHandler { Policy = new ThrottlePolicy(perSecond: 50, perMinute: 100, perHour: 200, perDay: 1500, perWeek: 3000) { IpThrottling = true }, Repository = new CacheRepository() }); config.Services.Add(typeof(IExceptionLogger), new NLogExceptionLogger(logger)); config.MapHttpAttributeRoutes(); // Go through our controllers and get the routes config.EnableSwagger(c => c.SingleApiVersion("v1", "Web Api Pattern - Framework")) .EnableSwaggerUi(); app.UseWebApi(config); }
public static void WhenAcceptHeaderStringHasQualityThenNegotiatedMediaTypeMatchesHigherQuality(string acceptHeader, string expected) { var actual = new DefaultContentNegotiator().Negotiate(new[] { "text/xml", "text/json" }, acceptHeader); Assert.AreEqual(expected, actual); }
public static void WhenAcceptHeaderIsMediaTypeThenNegotiatedMediaTypeMatches(string expected) { var actual = new DefaultContentNegotiator().Negotiate(new[] { "text/xml", "text/json" }, new[] { expected }); Assert.AreEqual(expected, actual); }
private static HttpConfiguration CreateHttpConfiguration() { Logger.Trace("UseHttpConfig: Begin HTTP Configuration."); var config = new HttpConfiguration(); config.EnableCors(new EnableCorsAttribute(origins: "*", headers: "*", methods: "* ")); config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "ResourceNotFound", routeTemplate: Resources.Constants.AppInfo.RoutePrefix + "/{*uri}", defaults: new { controller = "AppInfo", action = "ResourceNotFound" } ); //config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler()); //GlobalExceptionHandler.AppName = Resources.Constants.AppInfo.DisplayName; //GlobalExceptionHandler.AppVersion = Resources.Constants.AppInfo.Version; config.Services.Add(typeof(IExceptionLogger), new NLogExceptionLogger()); //config.Services.Replace(typeof(ITraceWriter), new NLogTraceWriter()); config.Services.Replace(typeof(IHttpControllerActivator), new SmServiceActivator(DependencyResolver.Container)); //config.MessageHandlers.Add(new RequireHttpsHandler()); //config.MessageHandlers.Add(new PreflightRequestsHandler()); //*** Register throttling handler ******************************************* // ++++ for more information: https://github.com/stefanprodan/WebApiThrottle config.MessageHandlers.Add(new ThrottlingHandler() { Policy = ThrottlePolicy.FromStore(new PolicyConfigurationProvider()), // throttle policy defined as xml in App.config (throttlePolicy) //PolicyRepository = new PolicyMemoryCacheRepository(), // can be accessed in code like (new PolicyCacheRepository()).FirstOrDefault(ThrottleManager.GetPolicyKey()) Repository = new MemoryCacheRepository() // uses the runtime memory cache for self-hosting WebApi with Owin. can use also Velocity, Redis or a NoSQL database }); config.Formatters.Clear(); config.Formatters.Add(new JsonMediaTypeFormatter()); config.Formatters.Add(new XmlMediaTypeFormatter()); config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter()); config.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json"); config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; config.Formatters.JsonFormatter.AddQueryStringMapping("format", "json", "application/json"); config.Formatters.JsonFormatter.AddRequestHeaderMapping("ReturnType", "json", StringComparison.InvariantCultureIgnoreCase, false, "application/json"); config.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "application/xml"); config.Formatters.XmlFormatter.AddQueryStringMapping("format", "xml", "application/xml"); config.Formatters.XmlFormatter.AddRequestHeaderMapping("ReturnType", "xml", StringComparison.InvariantCultureIgnoreCase, false, "application/xml"); DefaultContentNegotiator negotiator = new DefaultContentNegotiator(excludeMatchOnTypeOnly: true); config.Services.Replace(typeof(IContentNegotiator), negotiator); config.EnsureInitialized(); var isSwaggerEnabled = true; Boolean.TryParse(ConfigurationManager.AppSettings["EnableSwagger"], out isSwaggerEnabled); //if (isSwaggerEnabled) //{ // config.EnableSwagger("docs/{apiVersion}/swagger", c => // { // c.DescribeAllEnumsAsStrings(); // c.SingleApiVersion(Resources.Constants.AppInfo.Version, Resources.Constants.AppInfo.ProductName); // var authorityUri = new Uri(System.Configuration.ConfigurationManager.AppSettings["Authority"]); // c.OAuth2("oauth") // .AuthorizationUrl(authorityUri.ToString()) // .TokenUrl(new Uri(authorityUri, "connect/token").ToString()) // .Flow("resource_manager"); // }).EnableSwaggerUi(x => x.AddResourceOwnerFlowSupport()); //} Logger.Trace("UseHttpConfig: End HTTP Configuration."); return(config); }