public void HasProperSupportedEncodings() { // Arrange & Act var formatter = new XmlSerializerInputFormatter(new MvcOptions()); // Assert Assert.Contains(formatter.SupportedEncodings, i => i.WebName == "utf-8"); Assert.Contains(formatter.SupportedEncodings, i => i.WebName == "utf-16"); }
public void HasProperSupportedMediaTypes() { // Arrange & Act var formatter = new XmlSerializerInputFormatter(new MvcOptions()); // Assert Assert.Contains("application/xml", formatter.SupportedMediaTypes .Select(content => content.ToString())); Assert.Contains("text/xml", formatter.SupportedMediaTypes .Select(content => content.ToString())); }
public async Task BuffersRequestBody_ByDefault() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc); var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString>" + "<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>"; #pragma warning disable CS0618 var formatter = new XmlSerializerInputFormatter(); #pragma warning restore CS0618 var contentBytes = Encoding.UTF8.GetBytes(input); var httpContext = new DefaultHttpContext(); httpContext.Features.Set <IHttpResponseFeature>(new TestResponseFeature()); httpContext.Request.Body = new NonSeekableReadStream(contentBytes); httpContext.Request.ContentType = "application/json"; var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType <TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); Assert.Equal( XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc), model.SampleDate); Assert.True(httpContext.Request.Body.CanSeek); httpContext.Request.Body.Seek(0L, SeekOrigin.Begin); result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); model = Assert.IsType <TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); Assert.Equal( XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc), model.SampleDate); }
// Set up application services public void ConfigureServices(IServiceCollection services) { // Add MVC services to the services container services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Latest); services.Configure <MvcOptions>(options => { options.InputFormatters.Clear(); options.OutputFormatters.Clear(); // Since both XmlSerializer and DataContractSerializer based formatters // have supported media types of 'application/xml' and 'text/xml', it // would be difficult for a test to choose a particular formatter based on // request information (Ex: Accept header). // So here we instead clear out the default supported media types and create new // ones which are distinguishable between formatters. var xmlSerializerInputFormatter = new XmlSerializerInputFormatter(new MvcOptions()); xmlSerializerInputFormatter.SupportedMediaTypes.Clear(); xmlSerializerInputFormatter.SupportedMediaTypes.Add( new MediaTypeHeaderValue("application/xml-xmlser")); xmlSerializerInputFormatter.SupportedMediaTypes.Add( new MediaTypeHeaderValue("text/xml-xmlser")); var xmlSerializerOutputFormatter = new XmlSerializerOutputFormatter(); xmlSerializerOutputFormatter.SupportedMediaTypes.Clear(); xmlSerializerOutputFormatter.SupportedMediaTypes.Add( new MediaTypeHeaderValue("application/xml-xmlser")); xmlSerializerOutputFormatter.SupportedMediaTypes.Add( new MediaTypeHeaderValue("text/xml-xmlser")); var dcsInputFormatter = new XmlDataContractSerializerInputFormatter(new MvcOptions()); dcsInputFormatter.SupportedMediaTypes.Clear(); dcsInputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml-dcs")); dcsInputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml-dcs")); var dcsOutputFormatter = new XmlDataContractSerializerOutputFormatter(); dcsOutputFormatter.SupportedMediaTypes.Clear(); dcsOutputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml-dcs")); dcsOutputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml-dcs")); options.InputFormatters.Add(dcsInputFormatter); options.InputFormatters.Add(xmlSerializerInputFormatter); options.OutputFormatters.Add(dcsOutputFormatter); options.OutputFormatters.Add(xmlSerializerOutputFormatter); xmlSerializerInputFormatter.WrapperProviderFactories.Add(new PersonWrapperProviderFactory()); xmlSerializerOutputFormatter.WrapperProviderFactories.Add(new PersonWrapperProviderFactory()); dcsInputFormatter.WrapperProviderFactories.Add(new PersonWrapperProviderFactory()); dcsOutputFormatter.WrapperProviderFactories.Add(new PersonWrapperProviderFactory()); }); }
// Set up application services public void ConfigureServices(IServiceCollection services) { // Add MVC services to the services container services.AddMvc(); services.Configure<MvcOptions>(options => { options.InputFormatters.Clear(); options.OutputFormatters.Clear(); // Since both XmlSerializer and DataContractSerializer based formatters // have supported media types of 'application/xml' and 'text/xml', it // would be difficult for a test to choose a particular formatter based on // request information (Ex: Accept header). // So here we instead clear out the default supported media types and create new // ones which are distinguishable between formatters. var xmlSerializerInputFormatter = new XmlSerializerInputFormatter(); xmlSerializerInputFormatter.SupportedMediaTypes.Clear(); xmlSerializerInputFormatter.SupportedMediaTypes.Add( new MediaTypeHeaderValue("application/xml-xmlser")); xmlSerializerInputFormatter.SupportedMediaTypes.Add( new MediaTypeHeaderValue("text/xml-xmlser")); var xmlSerializerOutputFormatter = new XmlSerializerOutputFormatter(); xmlSerializerOutputFormatter.SupportedMediaTypes.Clear(); xmlSerializerOutputFormatter.SupportedMediaTypes.Add( new MediaTypeHeaderValue("application/xml-xmlser")); xmlSerializerOutputFormatter.SupportedMediaTypes.Add( new MediaTypeHeaderValue("text/xml-xmlser")); var dcsInputFormatter = new XmlDataContractSerializerInputFormatter(); dcsInputFormatter.SupportedMediaTypes.Clear(); dcsInputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml-dcs")); dcsInputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml-dcs")); var dcsOutputFormatter = new XmlDataContractSerializerOutputFormatter(); dcsOutputFormatter.SupportedMediaTypes.Clear(); dcsOutputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml-dcs")); dcsOutputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml-dcs")); options.InputFormatters.Add(dcsInputFormatter); options.InputFormatters.Add(xmlSerializerInputFormatter); options.OutputFormatters.Add(dcsOutputFormatter); options.OutputFormatters.Add(xmlSerializerOutputFormatter); xmlSerializerInputFormatter.WrapperProviderFactories.Add(new PersonWrapperProviderFactory()); xmlSerializerOutputFormatter.WrapperProviderFactories.Add(new PersonWrapperProviderFactory()); dcsInputFormatter.WrapperProviderFactories.Add(new PersonWrapperProviderFactory()); dcsOutputFormatter.WrapperProviderFactories.Add(new PersonWrapperProviderFactory()); }); }
public void CanRead_ReturnsFalse_ForAnyUnsupportedModelType(Type modelType, bool expectedCanRead) { // Arrange var formatter = new XmlSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes("content"); var context = GetInputFormatterContext(contentBytes, modelType); // Act var result = formatter.CanRead(context); // Assert Assert.Equal(expectedCanRead, result); }
public void CanRead_ReturnsFalse_ForAnyUnsupportedModelType(Type modelType, bool expectedCanRead) { // Arrange var formatter = new XmlSerializerInputFormatter(); var contentBytes = Encoding.UTF8.GetBytes("content"); var context = GetInputFormatterContext(contentBytes, modelType); // Act var result = formatter.CanRead(context); // Assert Assert.Equal(expectedCanRead, result); }
public void CanRead_ReturnsTrueForAnySupportedContentType(string requestContentType, bool expectedCanRead) { // Arrange var formatter = new XmlSerializerInputFormatter(); var contentBytes = Encoding.UTF8.GetBytes("content"); var actionContext = GetActionContext(contentBytes, contentType: requestContentType); var formatterContext = new InputFormatterContext(actionContext, typeof(string)); // Act var result = formatter.CanRead(formatterContext); // Assert Assert.Equal(expectedCanRead, result); }
public async Task ReadAsync_ThrowsOnExceededMaxDepth() { // Arrange var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelTwo><SampleString>test</SampleString>" + "<TestOne><SampleInt>10</SampleInt>" + "<sampleString>test</sampleString>" + "<SampleDate>" + XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc) + "</SampleDate></TestOne></TestLevelTwo>"; var formatter = new XmlSerializerInputFormatter(); formatter.MaxDepth = 1; var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo)); // Act & Assert await Assert.ThrowsAsync(typeof(InvalidOperationException), () => formatter.ReadAsync(context)); }
public async Task ReadAsync_ThrowsWhenReaderQuotasAreChanged() { // Arrange var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelTwo><SampleString>test</SampleString>" + "<TestOne><SampleInt>10</SampleInt>" + "<sampleString>test</sampleString>" + "<SampleDate>" + XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc) + "</SampleDate></TestOne></TestLevelTwo>"; var formatter = new XmlSerializerInputFormatter(new MvcOptions()); formatter.XmlDictionaryReaderQuotas.MaxStringContentLength = 10; var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo)); // Act & Assert await Assert.ThrowsAsync <InputFormatterException>(() => formatter.ReadAsync(context)); }
public async Task ReadAsync_VerifyStreamIsOpenAfterRead() { // Arrange var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<DummyClass><SampleInt>10</SampleInt></DummyClass>"; var formatter = new XmlSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(DummyClass)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); Assert.NotNull(result.Model); Assert.True(context.HttpContext.Request.Body.CanRead); }
public async Task SuppressInputFormatterBufferingSetToTrue_UsingMutatedOptions() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc); var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString>" + "<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>"; var mvcOptions = new MvcOptions(); mvcOptions.SuppressInputFormatterBuffering = false; var formatter = new XmlSerializerInputFormatter(mvcOptions); var contentBytes = Encoding.UTF8.GetBytes(input); var httpContext = new DefaultHttpContext(); httpContext.Features.Set <IHttpResponseFeature>(new TestResponseFeature()); httpContext.Request.Body = new NonSeekableReadStream(contentBytes); httpContext.Request.ContentType = "application/xml"; var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne)); // Act // Mutate options after passing into the constructor to make sure that the value type is not store in the constructor mvcOptions.SuppressInputFormatterBuffering = true; var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType <TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); Assert.Equal( XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc), model.SampleDate); // Reading again should fail as buffering request body is disabled await Assert.ThrowsAsync <XmlException>(() => formatter.ReadAsync(context)); }
public void CanRead_ReturnsTrueForAnySupportedContentType(string requestContentType, bool expectedCanRead) { // Arrange var formatter = new XmlSerializerInputFormatter(); var contentBytes = Encoding.UTF8.GetBytes("content"); var modelState = new ModelStateDictionary(); var httpContext = GetHttpContext(contentBytes, contentType: requestContentType); var formatterContext = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: modelState, modelType: typeof(string)); // Act var result = formatter.CanRead(formatterContext); // Assert Assert.Equal(expectedCanRead, result); }
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.Configure <MvcOptions>(options => { options.InputFormatters.Clear(); var jsonInputFormatter = new JsonInputFormatter(); jsonInputFormatter.SupportedMediaTypes.Clear(); jsonInputFormatter.SupportedMediaTypes.Add(JsonMediaType); options.InputFormatters.Add(jsonInputFormatter); var xmlSerializerInputFormatter = new XmlSerializerInputFormatter(); xmlSerializerInputFormatter.SupportedMediaTypes.Clear(); xmlSerializerInputFormatter.SupportedMediaTypes.Add(XmlSerializerMediaType); options.InputFormatters.Add(xmlSerializerInputFormatter); var xmlDataContractSerializerInputFormatter = new XmlDataContractSerializerInputFormatter(); xmlDataContractSerializerInputFormatter.SupportedMediaTypes.Clear(); xmlDataContractSerializerInputFormatter.SupportedMediaTypes.Add(XmlDataContractSerializerMediaType); options.InputFormatters.Add(xmlDataContractSerializerInputFormatter); options.OutputFormatters.Clear(); var jsonOutputFormatter = new JsonOutputFormatter(); jsonOutputFormatter.SupportedMediaTypes.Clear(); jsonOutputFormatter.SupportedMediaTypes.Add(JsonMediaType); options.OutputFormatters.Add(jsonOutputFormatter); var xmlSerializerOutputFormatter = new XmlSerializerOutputFormatter(); xmlSerializerOutputFormatter.SupportedMediaTypes.Clear(); xmlSerializerOutputFormatter.SupportedMediaTypes.Add(XmlSerializerMediaType); options.OutputFormatters.Add(xmlSerializerOutputFormatter); var xmlDataContractSerializerOutputFormatter = new XmlDataContractSerializerOutputFormatter(); xmlDataContractSerializerOutputFormatter.SupportedMediaTypes.Clear(); xmlDataContractSerializerOutputFormatter.SupportedMediaTypes.Add(XmlDataContractSerializerMediaType); options.OutputFormatters.Add(xmlDataContractSerializerOutputFormatter); }); }
public async Task SuppressInputFormatterBufferingSetToTrue_DoesNotBufferRequestBody_ObsoleteParameter() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc); var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString>" + "<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>"; #pragma warning disable CS0618 var formatter = new XmlSerializerInputFormatter(suppressInputFormatterBuffering: true); #pragma warning restore CS0618 var contentBytes = Encoding.UTF8.GetBytes(input); var httpContext = new DefaultHttpContext(); httpContext.Features.Set <IHttpResponseFeature>(new TestResponseFeature()); httpContext.Request.Body = new NonSeekableReadStream(contentBytes); httpContext.Request.ContentType = "application/xml"; var context = GetInputFormatterContext(httpContext, typeof(TestLevelOne)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType <TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); Assert.Equal( XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc), model.SampleDate); // Reading again should fail as buffering request body is disabled await Assert.ThrowsAsync <XmlException>(() => formatter.ReadAsync(context)); }
public async Task ReadAsync_AcceptsUTF16Characters() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc); var input = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString>" + "<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>"; var formatter = new XmlSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.Unicode.GetBytes(input); var modelState = new ModelStateDictionary(); var httpContext = GetHttpContext(contentBytes, contentType: "application/xml; charset=utf-16"); var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(typeof(TestLevelOne)); var context = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: modelState, metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType <TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); Assert.Equal(XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc), model.SampleDate); }
/// <summary> /// Adds the XML serializer formatters to <see cref="MvcOptions"/>. /// </summary> /// <param name="options">The <see cref="MvcOptions"/>.</param> public void Configure(MvcOptions options) { // Do not override any user mapping var key = "xml"; var mapping = options.FormatterMappings.GetMediaTypeMappingForFormat(key); if (string.IsNullOrEmpty(mapping)) { options.FormatterMappings.SetMediaTypeMappingForFormat( key, MediaTypeHeaderValues.ApplicationXml); } var inputFormatter = new XmlSerializerInputFormatter(options); inputFormatter.WrapperProviderFactories.Add(new ProblemDetailsWrapperProviderFactory()); options.InputFormatters.Add(inputFormatter); var outputFormatter = new XmlSerializerOutputFormatter(_loggerFactory); outputFormatter.WrapperProviderFactories.Add(new ProblemDetailsWrapperProviderFactory()); options.OutputFormatters.Add(outputFormatter); }
public async Task ReadAsync_ReadsWhenMaxDepthIsModified() { // Arrange var expectedInt = 10; var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<DummyClass><SampleInt>" + expectedInt + "</SampleInt></DummyClass>"; var formatter = new XmlSerializerInputFormatter(new MvcOptions()); formatter.MaxDepth = 10; var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(DummyClass)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType <DummyClass>(result.Model); Assert.Equal(expectedInt, model.SampleInt); }
public void CanRead_ReturnsTrueForAnySupportedContentType(string requestContentType, bool expectedCanRead) { // Arrange var formatter = new XmlSerializerInputFormatter(new MvcOptions()); var contentBytes = Encoding.UTF8.GetBytes("content"); var modelState = new ModelStateDictionary(); var httpContext = GetHttpContext(contentBytes, contentType: requestContentType); var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(typeof(string)); var formatterContext = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: modelState, metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); // Act var result = formatter.CanRead(formatterContext); // Assert Assert.Equal(expectedCanRead, result); }
public void CanRead_ReturnsTrueForAnySupportedContentType(string requestContentType, bool expectedCanRead) { // Arrange var formatter = new XmlSerializerInputFormatter(); var contentBytes = Encoding.UTF8.GetBytes("content"); var modelState = new ModelStateDictionary(); var httpContext = GetHttpContext(contentBytes, contentType: requestContentType); var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(typeof(string)); var formatterContext = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: modelState, metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); // Act var result = formatter.CanRead(formatterContext); // Assert Assert.Equal(expectedCanRead, result); }
public async Task ReadAsync_AcceptsUTF16Characters() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc); var input = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString>" + "<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>"; var formatter = new XmlSerializerInputFormatter(); var contentBytes = Encoding.Unicode.GetBytes(input); var modelState = new ModelStateDictionary(); var httpContext = GetHttpContext(contentBytes, contentType: "application/xml; charset=utf-16"); var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(typeof(TestLevelOne)); var context = new InputFormatterContext( httpContext, modelName: string.Empty, modelState: modelState, metadata: metadata); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); Assert.Equal(XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc), model.SampleDate); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(setupAction => { setupAction.ReturnHttpNotAcceptable = true; var xmlSerializerInputFormatter = new XmlSerializerInputFormatter(setupAction); setupAction.InputFormatters.Add(xmlSerializerInputFormatter); var jsonOutputFormatter = setupAction.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault(); if (jsonOutputFormatter != null) { jsonOutputFormatter.SupportedMediaTypes.Add("application/vnd.biob.json+hateoas"); } }) .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);; services.AddSwaggerGen(setupAction => { setupAction.EnableAnnotations(); setupAction.SwaggerDoc("v1", new Info { Title = "Biob RESTful api", Version = "v1" }); }); services.AddCors(); //services.AddCors(options => //{ // options.AddPolicy("default", policy => // { // policy.WithOrigins("http://localhost:3000") // .AllowAnyHeader() // .AllowAnyMethod(); // }); //}); //services.AddAuthorization(); services.AddAuthentication("Bearer") .AddIdentityServerAuthentication(options => { options.Authority = "https://localhost:44393/"; options.RequireHttpsMetadata = false; options.ApiName = "BiobApi"; }); //services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) // .AddIdentityServerAuthentication(options => // { // // IP of the identity server // options.Authority = "https://localhost:44393/"; // options.RequireHttpsMetadata = false; // options.ApiName = "Biob.Web.Api"; // }); //.AddJwtBearer(options => //{ // // needs to be configured // options.Authority = ""; // options.Audience = ""; //}); var connectionString = Configuration.GetConnectionString("BiobDB"); services.AddDbContext <BiobDataContext>(options => options.UseSqlServer(connectionString)); services.AddScoped <IMovieRepository, MovieRepository>(); services.AddScoped <IGenreRepository, GenreRepository>(); services.AddScoped <IMovieGenreRepository, MovieGenreRepository>(); services.AddScoped <ITicketRepository, TicketRepository>(); services.AddScoped <IHallRepository, HallRepository>(); services.AddScoped <ISeatRepository, SeatRepository>(); services.AddScoped <IShowtimeRepository, ShowtimeRepository>(); services.AddSingleton <IActionContextAccessor, ActionContextAccessor>(); services.AddScoped <IUrlHelper, UrlHelper>(implementationFactory => { var actionContext = implementationFactory.GetService <IActionContextAccessor>().ActionContext; return(new UrlHelper(actionContext)); }); services.AddTransient <IPropertyMappingService, PropertyMappingService>(); services.AddTransient <ITypeHelperService, TypeHelperService>(); services.AddHttpCacheHeaders( (expirationOptions) => { expirationOptions.MaxAge = 600; }, (validationOptions) => { validationOptions.MustRevalidate = true; validationOptions.Vary = new string[] { "Accept-Encoding" }; }); services.AddMemoryCache(); services.Configure <IpRateLimitOptions>(options => { options.GeneralRules = new List <RateLimitRule>() { // can add more rules but this is fine for now new RateLimitRule() { Endpoint = "*", Limit = 1000, Period = "15m" } }; }); services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>(); services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>(); }
// Set up application services public void ConfigureServices(IServiceCollection services) { // Add MVC services to the services container services.AddControllers() .AddXmlDataContractSerializerFormatters() .AddXmlSerializerFormatters(); services.Configure <MvcOptions>(options => { // Since both XmlSerializer and DataContractSerializer based formatters // have supported media types of 'application/xml' and 'text/xml', it // would be difficult for a test to choose a particular formatter based on // request information (Ex: Accept header). // We'll configure the ones on MvcOptions to use a distinct set of content types. XmlSerializerInputFormatter xmlSerializerInputFormatter = null; XmlSerializerOutputFormatter xmlSerializerOutputFormatter = null; XmlDataContractSerializerInputFormatter dcsInputFormatter = null; XmlDataContractSerializerOutputFormatter dcsOutputFormatter = null; for (var i = options.InputFormatters.Count - 1; i >= 0; i--) { switch (options.InputFormatters[i]) { case XmlSerializerInputFormatter formatter: xmlSerializerInputFormatter = formatter; break; case XmlDataContractSerializerInputFormatter formatter: dcsInputFormatter = formatter; break; default: options.InputFormatters.RemoveAt(i); break; } } for (var i = options.OutputFormatters.Count - 1; i >= 0; i--) { switch (options.OutputFormatters[i]) { case XmlSerializerOutputFormatter formatter: xmlSerializerOutputFormatter = formatter; break; case XmlDataContractSerializerOutputFormatter formatter: dcsOutputFormatter = formatter; break; default: options.OutputFormatters.RemoveAt(i); break; } } xmlSerializerInputFormatter.SupportedMediaTypes.Clear(); xmlSerializerInputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml-xmlser")); xmlSerializerInputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml-xmlser")); xmlSerializerInputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/problem+xml")); xmlSerializerOutputFormatter.SupportedMediaTypes.Clear(); xmlSerializerOutputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml-xmlser")); xmlSerializerOutputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml-xmlser")); xmlSerializerOutputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/problem+xml")); dcsInputFormatter.SupportedMediaTypes.Clear(); dcsInputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml-dcs")); dcsInputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml-dcs")); dcsInputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/problem+xml")); dcsOutputFormatter.SupportedMediaTypes.Clear(); dcsOutputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml-dcs")); dcsOutputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml-dcs")); dcsOutputFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/problem+xml")); options.InputFormatters.Add(dcsInputFormatter); options.InputFormatters.Add(xmlSerializerInputFormatter); options.OutputFormatters.Add(dcsOutputFormatter); options.OutputFormatters.Add(xmlSerializerOutputFormatter); xmlSerializerInputFormatter.WrapperProviderFactories.Add(new PersonWrapperProviderFactory()); xmlSerializerOutputFormatter.WrapperProviderFactories.Add(new PersonWrapperProviderFactory()); dcsInputFormatter.WrapperProviderFactories.Add(new PersonWrapperProviderFactory()); dcsOutputFormatter.WrapperProviderFactories.Add(new PersonWrapperProviderFactory()); }); }
public async Task ReadAsync_ThrowsWhenReaderQuotasAreChanged() { if (TestPlatformHelper.IsMono) { // ReaderQuotas are not honored on Mono return; } // Arrange var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelTwo><SampleString>test</SampleString>" + "<TestOne><SampleInt>10</SampleInt>" + "<sampleString>test</sampleString>" + "<SampleDate>" + XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc) + "</SampleDate></TestOne></TestLevelTwo>"; var formatter = new XmlSerializerInputFormatter(); formatter.XmlDictionaryReaderQuotas.MaxStringContentLength = 10; var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo)); // Act & Assert await Assert.ThrowsAsync(typeof(InvalidOperationException), () => formatter.ReadAsync(context)); }
public async Task ReadAsync_ReadsComplexTypes() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc); var expectedLevelTwoString = "102"; var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelTwo><SampleString>" + expectedLevelTwoString + "</SampleString>" + "<TestOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString>" + "<SampleDate>" + expectedDateTime + "</SampleDate></TestOne></TestLevelTwo>"; var formatter = new XmlSerializerInputFormatter(); var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo)); // Act var model = await formatter.ReadAsync(context); // Assert Assert.NotNull(model); Assert.IsType<TestLevelTwo>(model); var levelTwoModel = model as TestLevelTwo; Assert.Equal(expectedLevelTwoString, levelTwoModel.SampleString); Assert.Equal(expectedInt, levelTwoModel.TestOne.SampleInt); Assert.Equal(expectedString, levelTwoModel.TestOne.sampleString); Assert.Equal(XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc), levelTwoModel.TestOne.SampleDate); }
public async Task ReadAsync_AcceptsUTF16Characters() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc); var input = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString>" + "<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>"; var formatter = new XmlSerializerInputFormatter(); var contentBytes = Encodings.UTF16EncodingLittleEndian.GetBytes(input); var modelState = new ModelStateDictionary(); var httpContext = GetHttpContext(contentBytes, contentType: "application/xml; charset=utf-16"); var context = new InputFormatterContext(httpContext, modelState, typeof(TestLevelOne)); // Act var model = await formatter.ReadAsync(context); // Assert Assert.NotNull(model); Assert.IsType<TestLevelOne>(model); var levelOneModel = model as TestLevelOne; Assert.Equal(expectedInt, levelOneModel.SampleInt); Assert.Equal(expectedString, levelOneModel.sampleString); Assert.Equal(XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc), levelOneModel.SampleDate); }
public async Task ReadAsync_IgnoresBOMCharacters() { // Arrange var sampleString = "Test"; var sampleStringBytes = Encoding.UTF8.GetBytes(sampleString); var inputStart = Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + Environment.NewLine + "<TestLevelTwo><SampleString>" + sampleString); byte[] bom = { 0xef, 0xbb, 0xbf }; var inputEnd = Encoding.UTF8.GetBytes("</SampleString></TestLevelTwo>"); var expectedBytes = new byte[sampleString.Length + bom.Length]; var contentBytes = new byte[inputStart.Length + bom.Length + inputEnd.Length]; Buffer.BlockCopy(inputStart, 0, contentBytes, 0, inputStart.Length); Buffer.BlockCopy(bom, 0, contentBytes, inputStart.Length, bom.Length); Buffer.BlockCopy(inputEnd, 0, contentBytes, inputStart.Length + bom.Length, inputEnd.Length); var formatter = new XmlSerializerInputFormatter(); var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo)); // Act var model = await formatter.ReadAsync(context); // Assert Assert.NotNull(model); var levelTwoModel = model as TestLevelTwo; Buffer.BlockCopy(sampleStringBytes, 0, expectedBytes, 0, sampleStringBytes.Length); Buffer.BlockCopy(bom, 0, expectedBytes, sampleStringBytes.Length, bom.Length); Assert.Equal(expectedBytes, Encoding.UTF8.GetBytes(levelTwoModel.SampleString)); }
public async Task ReadAsync_UsesContentTypeCharSet_ToReadStream() { // Arrange var expectedException = TestPlatformHelper.IsMono ? typeof(InvalidOperationException) : typeof(XmlException); var expectedMessage = TestPlatformHelper.IsMono ? "There is an error in XML document." : "The expected encoding 'utf-16LE' does not match the actual encoding 'utf-8'."; var inputBytes = Encodings.UTF8EncodingWithoutBOM.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<DummyClass><SampleInt>1000</SampleInt></DummyClass>"); var formatter = new XmlSerializerInputFormatter(); var modelState = new ModelStateDictionary(); var httpContext = GetHttpContext(inputBytes, contentType: "application/xml; charset=utf-16"); var context = new InputFormatterContext(httpContext, modelState, typeof(TestLevelOne)); // Act and Assert var ex = await Assert.ThrowsAsync(expectedException, () => formatter.ReadAsync(context)); Assert.Equal(expectedMessage, ex.Message); }
public async Task ReadAsync_FallsbackToUTF8_WhenCharSet_NotInContentType() { // Arrange var expectedException = TestPlatformHelper.IsMono ? typeof(InvalidOperationException) : typeof(XmlException); var expectedMessage = TestPlatformHelper.IsMono ? "There is an error in XML document." : "The expected encoding 'utf-8' does not match the actual encoding 'utf-16LE'."; var inpStart = Encodings.UTF16EncodingLittleEndian.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-16\"?>" + "<DummyClass><SampleInt>"); byte[] inp = { 192, 193 }; var inpEnd = Encodings.UTF16EncodingLittleEndian.GetBytes("</SampleInt></DummyClass>"); var contentBytes = new byte[inpStart.Length + inp.Length + inpEnd.Length]; Buffer.BlockCopy(inpStart, 0, contentBytes, 0, inpStart.Length); Buffer.BlockCopy(inp, 0, contentBytes, inpStart.Length, inp.Length); Buffer.BlockCopy(inpEnd, 0, contentBytes, inpStart.Length + inp.Length, inpEnd.Length); var formatter = new XmlSerializerInputFormatter(); var context = GetInputFormatterContext(contentBytes, typeof(TestLevelTwo)); // Act and Assert var ex = await Assert.ThrowsAsync(expectedException, () => formatter.ReadAsync(context)); Assert.Equal(expectedMessage, ex.Message); }
public async Task ReadAsync_VerifyStreamIsOpenAfterRead() { // Arrange var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<DummyClass><SampleInt>10</SampleInt></DummyClass>"; var formatter = new XmlSerializerInputFormatter(); var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(DummyClass)); // Act var model = await formatter.ReadAsync(context); // Assert Assert.NotNull(model); Assert.True(context.HttpContext.Request.Body.CanRead); }
public void HasProperSuppportedEncodings() { // Arrange & Act var formatter = new XmlSerializerInputFormatter(); // Assert Assert.True(formatter.SupportedEncodings.Any(i => i.WebName == "utf-8")); Assert.True(formatter.SupportedEncodings.Any(i => i.WebName == "utf-16")); }
public async Task ReadAsync_ReadsSimpleTypes() { // Arrange var expectedInt = 10; var expectedString = "TestString"; var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc); var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" + "<sampleString>" + expectedString + "</sampleString>" + "<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>"; var formatter = new XmlSerializerInputFormatter(); var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(TestLevelOne)); // Act var result = await formatter.ReadAsync(context); // Assert Assert.NotNull(result); Assert.False(result.HasError); var model = Assert.IsType<TestLevelOne>(result.Model); Assert.Equal(expectedInt, model.SampleInt); Assert.Equal(expectedString, model.sampleString); Assert.Equal( XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc), model.SampleDate); }
public void HasProperSuppportedMediaTypes() { // Arrange & Act var formatter = new XmlSerializerInputFormatter(); // Assert Assert.True(formatter.SupportedMediaTypes .Select(content => content.ToString()) .Contains("application/xml")); Assert.True(formatter.SupportedMediaTypes .Select(content => content.ToString()) .Contains("text/xml")); }
public void SetMaxDepth_ThrowsWhenMaxDepthIsBelowOne() { // Arrange var formatter = new XmlSerializerInputFormatter(); // Act & Assert Assert.Throws(typeof(ArgumentException), () => formatter.MaxDepth = 0); }
public async Task ReadAsync_ReadsWhenMaxDepthIsModified() { // Arrange var expectedInt = 10; var input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<DummyClass><SampleInt>" + expectedInt + "</SampleInt></DummyClass>"; var formatter = new XmlSerializerInputFormatter(); formatter.MaxDepth = 10; var contentBytes = Encoding.UTF8.GetBytes(input); var context = GetInputFormatterContext(contentBytes, typeof(DummyClass)); // Act var model = await formatter.ReadAsync(context); // Assert Assert.NotNull(model); Assert.IsType<DummyClass>(model); var dummyModel = model as DummyClass; Assert.Equal(expectedInt, dummyModel.SampleInt); }