private HtmlString SerializeInternal(JsonOutputFormatter jsonOutputFormatter, object value) { var stringWriter = new StringWriter(CultureInfo.InvariantCulture); jsonOutputFormatter.WriteObject(stringWriter, value); return new HtmlString(stringWriter.ToString()); }
public async Task CustomSerializerSettingsObject_TakesEffect() { // Arrange var person = new User() { Name = "John", Age = 35 }; var expectedOutput = JsonConvert.SerializeObject(person, new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver(), Formatting = Formatting.Indented }); var jsonFormatter = new JsonOutputFormatter(); jsonFormatter.SerializerSettings = new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver(), Formatting = Formatting.Indented }; var outputFormatterContext = GetOutputFormatterContext(person, typeof(User)); // Act await jsonFormatter.WriteResponseBodyAsync(outputFormatterContext); // Assert Assert.NotNull(outputFormatterContext.ActionContext.HttpContext.Response.Body); outputFormatterContext.ActionContext.HttpContext.Response.Body.Position = 0; var streamReader = new StreamReader(outputFormatterContext.ActionContext.HttpContext.Response.Body, Encoding.UTF8); Assert.Equal(expectedOutput, streamReader.ReadToEnd()); }
public void Creates_SerializerSettings_ByDefault() { // Arrange // Act var jsonFormatter = new JsonOutputFormatter(); // Assert Assert.NotNull(jsonFormatter.SerializerSettings); }
public override void OnActionExecuted(ActionExecutedContext context) { var result = context.Result as ObjectResult; if (result != null) { result.Formatters.Add(new PlainTextFormatter()); result.Formatters.Add(new CustomFormatter("application/custom")); var jsonFormatter = new JsonOutputFormatter(); jsonFormatter.SerializerSettings.Formatting = Formatting.Indented; result.Formatters.Add(jsonFormatter); } base.OnActionExecuted(context); }
public IActionResult ReturnsIndentedJson() { var user = new User() { Id = 1, Alias = "john", description = "Administrator", Designation = "Administrator", Name = "John Williams" }; var jsonFormatter = new JsonOutputFormatter(); jsonFormatter.SerializerSettings.Formatting = Formatting.Indented; var objectResult = new ObjectResult(user); objectResult.Formatters.Add(jsonFormatter); return objectResult; }
// This method gets called by the runtime. Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddApplicationInsightsTelemetry(Configuration); services.AddMvc(); services.AddEntityFramework() .AddSqlServer() .AddDbContext<ContactsDBContext>(options => { options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]); }); services.Configure<MvcOptions>(options => { var jsonFormatter = new JsonOutputFormatter { SerializerSettings = { ContractResolver = new CamelCasePropertyNamesContractResolver(), DefaultValueHandling = DefaultValueHandling.Ignore } }; options.OutputFormatters.RemoveType<JsonOutputFormatter>(); options.OutputFormatters.Insert(0, jsonFormatter); }); services.AddTransient<IContactsRepository, ContactsRepository>(); services.AddCors(options => { options.AddPolicy( "CorsTutaureliaNet", builder => { builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod(); }); }); }
private void ConfigureMvc(MvcOptions options) { options.CacheProfiles.Add(Constants.CacheProfileName, new CacheProfile() { Duration = Configuration.Get("CacheDuration", 10), VaryByHeader = "Accept" } ); var jsonOutputFormatter = new JsonOutputFormatter { SerializerSettings = { ContractResolver = new CamelCasePropertyNamesContractResolver(), DefaultValueHandling = DefaultValueHandling.Include } }; options.OutputFormatters.RemoveType<JsonOutputFormatter>(); options.OutputFormatters.Insert(0, jsonOutputFormatter); }
public void ProvidesVariablesInContinuousDeliveryModeForFeatureBranchWithCustomAssemblyInformationalFormat() { var semVer = new SemanticVersion { Major = 1, Minor = 2, Patch = 3, BuildMetaData = "5.Branch.feature/123" }; semVer.BuildMetaData.Branch = "feature/123"; semVer.BuildMetaData.VersionSourceSha = "versionSourceSha"; semVer.BuildMetaData.Sha = "commitSha"; semVer.BuildMetaData.ShortSha = "commitShortSha"; semVer.BuildMetaData.CommitDate = DateTimeOffset.Parse("2014-03-06 23:59:59Z"); var config = new TestEffectiveConfiguration(assemblyInformationalFormat: "{Major}.{Minor}.{Patch}+{CommitsSinceVersionSource}.Branch.{BranchName}.Sha.{ShortSha}"); var vars = variableProvider.GetVariablesFor(semVer, config, false); JsonOutputFormatter.ToJson(vars).ShouldMatchApproved(c => c.SubFolder("Approved")); }
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddDataProtection(); services.AddMvc() .AddMvcOptions(options => { var jsonOutputFormatter = new JsonOutputFormatter(); jsonOutputFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); options.OutputFormatters.Insert(0, jsonOutputFormatter); }); services.AddCors(); var policy = new Microsoft.AspNet.Cors.Core.CorsPolicy(); policy.Headers.Add("*"); policy.Methods.Add("*"); policy.Origins.Add("*"); policy.SupportsCredentials = true; services.AddCors(o => o.AddPolicy("mypolicy", policy)); }
public async Task WriteToStreamAsync_RoundTripsJToken() { // Arrange var beforeMessage = "Hello World"; var formatter = new JsonOutputFormatter(); var before = new JValue(beforeMessage); var memStream = new MemoryStream(); var outputFormatterContext = GetOutputFormatterContext( beforeMessage, typeof(string), "application/json; charset=utf-8", memStream); // Act await formatter.WriteResponseBodyAsync(outputFormatterContext); // Assert memStream.Position = 0; var after = JToken.Load(new JsonTextReader(new StreamReader(memStream))); var afterMessage = after.ToObject <string>(); Assert.Equal(beforeMessage, afterMessage); }
public void ProvidesVariablesInContinuousDeliveryModeForPreReleaseWithPadding() { var semVer = new SemanticVersion { Major = 1, Minor = 2, Patch = 3, PreReleaseTag = "unstable.4", BuildMetaData = "5.Branch.develop" }; semVer.BuildMetaData.VersionSourceSha = "versionSourceSha"; semVer.BuildMetaData.Sha = "commitSha"; semVer.BuildMetaData.ShortSha = "commitShortSha"; semVer.BuildMetaData.CommitDate = DateTimeOffset.Parse("2014-03-06 23:59:59Z"); var config = new TestEffectiveConfiguration(buildMetaDataPadding: 2, legacySemVerPadding: 5); var vars = variableProvider.GetVariablesFor(semVer, config, false); JsonOutputFormatter.ToJson(vars).ShouldMatchApproved(c => c.SubFolder("Approved")); }
public void ProvidesVariablesInContinuousDeploymentModeForStableWhenCurrentCommitIsTagged() { var semVer = new SemanticVersion { Major = 1, Minor = 2, Patch = 3, BuildMetaData = { CommitsSinceTag = 5, CommitsSinceVersionSource = 5, Sha = "commitSha", ShortSha = "commitShortSha", CommitDate = DateTimeOffset.Parse("2014-03-06 23:59:59Z") } }; var config = new TestEffectiveConfiguration(versioningMode: VersioningMode.ContinuousDeployment); var vars = VariableProvider.GetVariablesFor(semVer, config, true); JsonOutputFormatter.ToJson(vars).ShouldMatchApproved(c => c.SubFolder("Approved")); }
public void Json() { var semanticVersion = new SemanticVersion { Major = 1, Minor = 2, Patch = 0, PreReleaseTag = "unstable4", BuildMetaData = new SemanticVersionBuildMetaData("versionSourceSha", 5, "feature1", "commitSha", "commitShortSha", DateTimeOffset.Parse("2014-03-06 23:59:59Z")) }; var config = new TestEffectiveConfiguration(); var log = new NullLog(); var metaDataCalculator = new MetaDataCalculator(); var baseVersionCalculator = new BaseVersionCalculator(log, null); var mainlineVersionCalculator = new MainlineVersionCalculator(log, metaDataCalculator); var nextVersionCalculator = new NextVersionCalculator(log, metaDataCalculator, baseVersionCalculator, mainlineVersionCalculator); var variableProvider = new VariableProvider(nextVersionCalculator, new TestEnvironment()); var variables = variableProvider.GetVariablesFor(semanticVersion, config, false); var json = JsonOutputFormatter.ToJson(variables); json.ShouldMatchApproved(c => c.SubFolder("Approved")); }
private static void SetupMvcOptions(MvcOptions setupAction) { setupAction.ReturnHttpNotAcceptable = true; setupAction.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); XmlDataContractSerializerInputFormatter xmlDataContractSerializerInputFormatter = new XmlDataContractSerializerInputFormatter(); xmlDataContractSerializerInputFormatter.SupportedMediaTypes.Add( "application/vnd.marvin.authorwithdateofdeath.full+xml"); setupAction.InputFormatters.Add(xmlDataContractSerializerInputFormatter); JsonOutputFormatter jsonOutputFormatter = setupAction.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault(); jsonOutputFormatter?.SupportedMediaTypes.Add(VendorMediaType); JsonInputFormatter jsonInputFormatter = setupAction.InputFormatters.OfType <JsonInputFormatter>().FirstOrDefault(); jsonInputFormatter?.SupportedMediaTypes.Add("application/vnd.marvin.author.full+json"); jsonInputFormatter?.SupportedMediaTypes.Add("application/vnd.marvin.authorwithdateofdeath.full+json"); }
// This method gets called by a runtime. // Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); services.AddMvc(); // Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers. // You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json. // services.AddWebApiConventions(); // Add Scoped = Resolve dependency injection services.AddScoped<LibraryDbContext, LibraryDbContext>(); services.AddScoped<IMediatheekService, MediatheekService>(); // Add Entity Framework services to the services container. services.AddEntityFramework() .AddSqlite() .AddDbContext<LibraryDbContext>(options => options.UseSqlite(Configuration["Data:DefaultConnection:ConnectionString"])); // Formatter JSON services.Configure<MvcOptions>(options => { var jsonOutputFormatter = new JsonOutputFormatter(); jsonOutputFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); jsonOutputFormatter.SerializerSettings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore; jsonOutputFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; jsonOutputFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.None; options.OutputFormatters.Insert(0, jsonOutputFormatter); options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAll")); }); }
public async Task CustomSerializerSettingsObject_TakesEffect() { // Arrange var person = new User() { Name = "John", Age = 35 }; var expectedOutput = JsonConvert.SerializeObject(person, new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver(), Formatting = Formatting.Indented }); var jsonFormatter = new JsonOutputFormatter(); jsonFormatter.SerializerSettings = new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver(), Formatting = Formatting.Indented }; var outputFormatterContext = GetOutputFormatterContext(person, typeof(User)); // Act await jsonFormatter.WriteResponseBodyAsync(outputFormatterContext); // Assert var body = outputFormatterContext.HttpContext.Response.Body; Assert.NotNull(body); body.Position = 0; var content = new StreamReader(body, Encoding.UTF8).ReadToEnd(); Assert.Equal(expectedOutput, content); }
public IServiceProvider ConfigureServices(IServiceCollection services) { var settingsManager = Configuration.LoadSettings <AppSettings>(options => { options.SetConnString(x => x.SlackNotifications.AzureQueue.ConnectionString); options.SetQueueName(x => x.SlackNotifications.AzureQueue.QueueName); options.SenderName = $"{AppEnvironment.Name} {AppEnvironment.Version}"; }); #if !DEBUG services.AddApplicationInsightsTelemetry(); #endif services.AddAutoMapper(typeof(AutoMapperProfile)); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddMvcOptions(opt => { opt.Filters.Add(typeof(NoContentFilter)); }) .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); options.SerializerSettings.Converters.Add(new StringEnumConverter()); }) .AddFluentValidation(opt => { opt.RegisterValidatorsFromAssembly(Assembly.GetEntryAssembly()); }); services.Configure <MvcOptions>(opts => { var formatter = opts.OutputFormatters.FirstOrDefault(i => i.GetType() == typeof(JsonOutputFormatter)); var jsonFormatter = formatter as JsonOutputFormatter; var formatterSettings = jsonFormatter == null ? JsonSerializerSettingsProvider.CreateSerializerSettings() : jsonFormatter.PublicSerializerSettings; if (formatter != null) { opts.OutputFormatters.RemoveType <JsonOutputFormatter>(); } formatterSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ss.fffZ"; var jsonOutputFormatter = new JsonOutputFormatter(formatterSettings, ArrayPool <char> .Create()); opts.OutputFormatters.Insert(0, jsonOutputFormatter); }); _appSettings = settingsManager.CurrentValue; services.AddSwaggerGen(options => { options.DefaultLykkeConfiguration(ApiVersion, ApiTitle); options.OperationFilter <ObsoleteOperationDescriptionFilter>(); options.OperationFilter <ApiKeyHeaderOperationFilter>(); }); services.Configure <ApiBehaviorOptions>(options => { // Wrap failed model state into LykkeApiErrorResponse. //options.InvalidModelStateResponseFactory = InvalidModelStateResponseFactory.CreateInvalidModelResponse; }); services.AddAuthentication(o => { o.DefaultForbidScheme = IISDefaults.AuthenticationScheme; }); services.AddLykkeLogging( settingsManager.ConnectionString(s => s.AdminApiService.Db.LogsConnString), "AdminApiServiceLogs", _appSettings.SlackNotifications.AzureQueue.ConnectionString, _appSettings.SlackNotifications.AzureQueue.QueueName, logBuilder => logBuilder .AddSanitizingFilter(new Regex(@"(\\?""?[Pp]assword\\?""?:\s*\\?"")(.*?)(\\?"")"), "$1*$3") .AddSanitizingFilter(new Regex(@"(\\?""?[Ll]ogin\\?""?:\s*\\?"")(.*?)(\\?"")"), "$1*$3") .AddSanitizingFilter(new Regex(@"(\\?""?[Ee]mail\\?""?:\s*\\?"")(.*?)(\\?"")"), "$1*$3")); var builder = new ContainerBuilder(); builder.Populate(services); builder.RegisterModule(new AutofacModule(settingsManager)); var adminSettings = settingsManager.CurrentValue.AdminApiService; builder.RegisterModule( new DomainServices.AutofacModule( adminSettings.TokenSymbol, adminSettings.IsPublicBlockchainFeatureDisabled, adminSettings.MobileAppImageDoOptimization, adminSettings.MobileAppImageMinWidth, adminSettings.MobileAppImageWarningFileSizeInKB, adminSettings.SuggestedAdminPasswordLength, adminSettings.IsPhoneVerificationDisabled)); ApplicationContainer = builder.Build(); InvalidModelStateResponseFactory.Logger = ApplicationContainer.Resolve <ILogFactory>() .CreateLog(nameof(InvalidModelStateResponseFactory)); return(new AutofacServiceProvider(ApplicationContainer)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add EF services to the services container. services.AddEntityFramework() .AddSqlServer() .AddDbContext<NerdDinnerDbContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); services.AddScoped<INerdDinnerRepository, NerdDinnerRepository>(); // Add Identity services to the services container. services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<NerdDinnerDbContext>() .AddDefaultTokenProviders(); //services.ConfigureFacebookAuthentication(options => //{ // options.ClientId = Configuration["Authentication:Facebook:AppId"]; // options.ClientSecret = Configuration["Authentication:Facebook:AppSecret"]; //}); //services.ConfigureGoogleAuthentication(options => //{ // options.ClientId = Configuration["Authentication:Google:AppId"]; // options.ClientSecret = Configuration["Authentication:Google:AppSecret"]; //}); //services.ConfigureTwitterAuthentication(options => //{ // options.ConsumerKey = Configuration["Authentication:Twitter:AppId"]; // options.ConsumerSecret = Configuration["Authentication:Twitter:AppSecret"]; //}); //services.ConfigureMicrosoftAccountAuthentication(options => //{ // options.Caption = "MicrosoftAccount - Requires project changes"; // options.ClientId = Configuration["Authentication:Microsoft:AppId"]; // options.ClientSecret = Configuration["Authentication:Microsoft:AppSecret"]; //}); // Add MVC services to the services container. services.AddMvc().Configure<MvcOptions>(options => { var settings = new JsonSerializerSettings() { Formatting = Formatting.Indented, ContractResolver = new CamelCasePropertyNamesContractResolver() }; var formatter = new JsonOutputFormatter { SerializerSettings = settings }; options.OutputFormatters.Insert(0, formatter); // Add validation filters options.Filters.Add(new ValidateModelFilterAttribute()); }); }
public JsonWriter(JsonOutputFormatter formatter) { _formatter = formatter; }
private static Encoding CreateOrGetSupportedEncoding( JsonOutputFormatter formatter, string encodingAsString, bool isDefaultEncoding) { Encoding encoding = null; if (isDefaultEncoding) { encoding = formatter.SupportedEncodings .First((e) => e.WebName.Equals(encodingAsString, StringComparison.OrdinalIgnoreCase)); } else { encoding = Encoding.GetEncoding(encodingAsString); formatter.SupportedEncodings.Add(encoding); } return encoding; }
public IServiceProvider ConfigureServices(IServiceCollection services) { var settingsManager = Configuration.LoadSettings <AppSettings>(options => { options.SetConnString(x => x.SlackNotifications.AzureQueue.ConnectionString); options.SetQueueName(x => x.SlackNotifications.AzureQueue.QueueName); options.SenderName = $"{AppEnvironment.Name} {AppEnvironment.Version}"; }); #if !DEBUG services.AddApplicationInsightsTelemetry(); #endif services.AddAutoMapper(typeof(AutoMapperProfile)); services.AddHttpClient(); services .AddMvc(opts => { opts.Filters.Add(typeof(MaintenanceFilter)); opts.Filters.Add(typeof(NoContentFilter)); }) .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); options.SerializerSettings.Converters.Add(new StringEnumConverter()); }) .AddFluentValidation(fv => fv.RegisterValidatorsFromAssembly(Assembly.GetEntryAssembly())); services.Configure <MvcOptions>(opts => { var formatter = opts.OutputFormatters.FirstOrDefault(i => i.GetType() == typeof(JsonOutputFormatter)); var jsonFormatter = formatter as JsonOutputFormatter; var formatterSettings = jsonFormatter == null ? JsonSerializerSettingsProvider.CreateSerializerSettings() : jsonFormatter.PublicSerializerSettings; if (formatter != null) { opts.OutputFormatters.RemoveType <JsonOutputFormatter>(); } formatterSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ss.fffZ"; var jsonOutputFormatter = new JsonOutputFormatter(formatterSettings, ArrayPool <char> .Create()); opts.OutputFormatters.Insert(0, jsonOutputFormatter); }); _appSettings = settingsManager.CurrentValue; services.AddSwaggerGen(options => { options.DefaultLykkeConfiguration(ApiVersion, ApiTitle); options.OperationFilter <ObsoleteOperationDescriptionFilter>(); options.OperationFilter <ApiKeyHeaderOperationFilter>(); }); services.Configure <ApiBehaviorOptions>(options => { // Wrap failed model state into LykkeApiErrorResponse. options.InvalidModelStateResponseFactory = InvalidModelStateResponseFactory.CreateInvalidModelResponse; }); services.AddLykkeLogging( settingsManager.ConnectionString(s => s.CustomerApiService.Db.LogsConnString), "CustomerApiServiceLogs", _appSettings.SlackNotifications.AzureQueue.ConnectionString, _appSettings.SlackNotifications.AzureQueue.QueueName, logBuilder => logBuilder .AddSanitizingFilter(new Regex(@"(\\?""?[Pp]assword\\?""?:\s*\\?"")(.*?)(\\?"")"), "$1*$3") .AddSanitizingFilter(new Regex(@"(\\?""?[Ll]ogin\\?""?:\s*\\?"")(.*?)(\\?"")"), "$1*$3") .AddSanitizingFilter(new Regex(@"(\\?""?[Ee]mail\\?""?:\s*\\?"")(.*?)(\\?"")"), "$1*$3") .AddSanitizingFilter(new Regex(@"(\\?""?[Pp]hone[Nn]umber\\?""?:\s*\\?"")(.*?)(\\?"")"), "$1*$3") .AddSanitizingFilter(new Regex(@"(\\?""?[Cc]ontent\\?""?:\s*\\?"")(.*?)(\\?"")"), "$1*$3")); // Initialize number of decimal digits for Money18 type. Money18Extensions.NumberDecimalPlaces = _appSettings.CustomerApiService.NumberDecimalPlaces; var builder = new ContainerBuilder(); builder.Populate(services); builder.RegisterModule(new ServiceModule(settingsManager)); builder.RegisterModule(new ClientsModule(settingsManager)); builder.RegisterModule(new AspNetCoreModule()); builder.RegisterModule(new RepositoriesModule(settingsManager)); ApplicationContainer = builder.Build(); return(new AutofacServiceProvider(ApplicationContainer)); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { // string path = "D://VisualStudioProject//VisualCore//artifacts//bin//EmployeeWebApi//Debug//dnx451//EmployeeWebApi.xml"; //Add framework services. //services.AddApplicationInsightsTelemetry(Configuration); // services.AddEntityFramework() // .AddSqlServer() // .AddDbContext<ApplicationDbContext>(options => // options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])); services.AddEntityFramework() .AddSqlite() .AddDbContext <ApplicationDbContext>(options => options.UseSqlite(Configuration["Data:DefaultConnection:ConnectionString"])); services.AddIdentity <ApplicationUser, IdentityRole>() .AddEntityFrameworkStores <ApplicationDbContext>() .AddDefaultTokenProviders(); services.AddMvc(options => { var jsonOutputFormatter = new JsonOutputFormatter(); jsonOutputFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; options.OutputFormatters.Clear(); options.OutputFormatters.Add(jsonOutputFormatter); }); //Add Entity Framework services.AddEntityFramework() .AddSqlite() .AddDbContext <EmployeeDbContext>(options => options.UseSqlite (Configuration["Data:DefaultConnection:ConnectionString"])); ////Swagger services.AddSwaggerGen(); services.ConfigureSwaggerDocument(options => { options.SingleApiVersion(new Info { Version = "v1", Title = "Geo Search API", Description = "A simple api for crud operations in employee", TermsOfService = "None" }); options.OperationFilter(new Swashbuckle.SwaggerGen.XmlComments.ApplyXmlActionComments(pathToDoc)); }); services.ConfigureSwaggerSchema(options => { options.DescribeAllEnumsAsStrings = true; options.ModelFilter(new Swashbuckle.SwaggerGen.XmlComments.ApplyXmlTypeComments(pathToDoc)); }); // Add application services. services.AddTransient <IEmailSender, AuthMessageSender>(); services.AddTransient <ISmsSender, AuthMessageSender>(); var builder = new ContainerBuilder(); builder.RegisterModule(new AutofacModule()); builder.Populate(services); var container = builder.Build(); return(container.Resolve <IServiceProvider>()); }
public virtual JsonResult Json <T>([NotNull] T content, [NotNull] JsonSerializerSettings serializerSettings) { var formatter = new JsonOutputFormatter(serializerSettings); return(new JsonResult(content, formatter)); }
/// <inheritdoc /> public HtmlString Serialize(object value, [NotNull] JsonSerializerSettings serializerSettings) { var jsonOutputFormatter = new JsonOutputFormatter(serializerSettings); return SerializeInternal(jsonOutputFormatter, value); }
public static IMvcBuilder AddApiExtensions(this IMvcBuilder builder, IConfigurationSection config = null, Action <ApiExtensionOptions> build = null) { var apiOptions = new ApiExtensionOptions(); #region Include services needed for building uri's in the paging object builder.Services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>(); builder.Services.TryAddSingleton <IActionContextAccessor, ActionContextAccessor>(); builder.Services.AddScoped <IUrlHelper>(x => { var actionContext = x.GetService <IActionContextAccessor>().ActionContext; return(new UrlHelper(actionContext)); }); builder.Services.TryAddSingleton <ILinkProvider, LinkProvider>(); #endregion #region Register Options if (config != null && build != null) { builder.Services.Configure <ApiExtensionOptions>(x => { }); } if (config != null) { builder.Services.Configure <ApiExtensionOptions>(config); config.Bind(apiOptions); } if (build != null) { builder.Services.Configure <ApiExtensionOptions>(build); build(apiOptions); } #endregion #region Configuration from options if (!apiOptions.DisableGlobalErrorHandling && !apiOptions.DisableGlobalExceptionFilter) { builder.AddMvcOptions(options => { options.Filters.Add(typeof(GlobalExceptionFilter)); }); } if (!apiOptions.DisableVersioning) { builder.AddMvcOptions(options => { options.Conventions.Insert(0, new RouteConvention(new RouteAttribute("{apiVersion}"))); }); } #endregion builder.AddMvcOptions(options => { options.Filters.Insert(0, new ConsumesAttribute("application/json")); options.Filters.Insert(1, new ProducesAttribute("application/json")); options.ModelBinderProviders.Insert(0, new CommaDelimitedArrayModelBinderProvider()); JsonOutputFormatter jsonFormatter = options.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault(); jsonFormatter?.SupportedMediaTypes.Add("application/hal+json"); }); builder.AddJsonOptions(x => { x.SerializerSettings.ContractResolver = new BaseContractResolver(); x.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; x.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; x.SerializerSettings.Converters.Add(new TimeSpanConverter()); x.SerializerSettings.Converters.Add(new PagedResultConverter()); x.SerializerSettings.Converters.Add(new GuidConverter()); x.SerializerSettings.Formatting = Formatting.None; }); return(builder); }
/// <summary> /// 注册Workflow Rest服务 /// </summary> /// <param name="mvcBuilder"></param> /// <param name="config"></param> /// <returns></returns> public static IMvcBuilder AddProcessEngineRestServices(this IMvcBuilder mvcBuilder, IConfiguration config) { IServiceCollection services = mvcBuilder.Services; services.AddAuthorization(opts => { opts.AddPolicy(WorkflowConstants.WORKFLOW_AUTHORIZE_POLICY, policy => { policy.Requirements.Add(new InternaWorkflowAuthorizationRequirement()); }); }); services.AddSingleton <IAuthorizationHandler, InternalWorkflowAuthorizationHandler>(); services.UseInMemoryBus(); mvcBuilder.AddMvcOptions(opts => { #if !NETCORE3 JsonOutputFormatter jsonFormatter = opts.OutputFormatters.FirstOrDefault(x => x.GetType() == typeof(JsonOutputFormatter)) as JsonOutputFormatter; if (jsonFormatter != null) { jsonFormatter.PublicSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; } #endif opts.ModelBinderProviders.Insert(0, new PageableModelBinderProvider()); #if NETCORE3 SystemTextJsonOutputFormatter jsonFormatter = opts.OutputFormatters.FirstOrDefault(x => x.GetType() == typeof(SystemTextJsonOutputFormatter)) as SystemTextJsonOutputFormatter; opts.EnableEndpointRouting = false; #endif }); #if NETCORE3 mvcBuilder.AddNewtonsoftJson(opts => { opts.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; }); #endif services.AddTransient <ProcessInstanceSortApplier>(); services.AddSingleton <PageRetriever>(); services.AddTransient <HistoricInstanceConverter>(); services.AddTransient <HistoryInstanceSortApplier>(); services.AddTransient <PageableProcessHistoryRepositoryService>(); services.AddTransient <PageableProcessInstanceRepositoryService>(sp => { IProcessEngine engine = sp.GetService <IProcessEngine>(); return(new PageableProcessInstanceRepositoryService(sp.GetService <PageRetriever>(), engine.RuntimeService, sp.GetService <ProcessInstanceSortApplier>(), sp.GetService <ProcessInstanceConverter>(), sp.GetService <ILoggerFactory>())); }); services.AddTransient <ListConverter>(); services.AddTransient <TaskConverter>(sp => new TaskConverter(sp.GetService <ListConverter>())); services.AddTransient <HistoricTaskInstanceConverter>(sp => new HistoricTaskInstanceConverter(sp.GetService <ListConverter>())); services.AddTransient <TaskSortApplier>(); services.AddTransient <HistoryTaskSortApplier>(); //services.AddTransient<MessageProducerActivitiEventListener>(); services.AddTransient <PageableTaskRepositoryService>(sp => { IProcessEngine engine = sp.GetService <IProcessEngine>(); return(new PageableTaskRepositoryService( engine.TaskService, sp.GetService <TaskConverter>(), sp.GetService <HistoricTaskInstanceConverter>(), sp.GetService <IHistoryService>(), sp.GetService <PageRetriever>(), sp.GetService <TaskSortApplier>(), sp.GetService <HistoryTaskSortApplier>())); }); services.AddTransient <ProcessInstanceConverter>(sp => { IProcessEngine engine = sp.GetService <IProcessEngine>(); return(new ProcessInstanceConverter(sp.GetService <ListConverter>())); }); services.AddTransient <ProcessInstanceResourceAssembler>(); services.AddScoped <ProcessEngineWrapper>(sp => { IProcessEngine engine = sp.GetService <IProcessEngine>(); IHttpContextAccessor httpContext = sp.GetService <IHttpContextAccessor>(); return(new ProcessEngineWrapper(sp.GetService <ProcessInstanceConverter>(), sp.GetService <PageableProcessInstanceRepositoryService>(), sp.GetService <TaskConverter>(), sp.GetService <PageableTaskRepositoryService>(), null, sp.GetService <SecurityPoliciesApplicationService>(), null, sp.GetService <IApplicationEventPublisher>(), engine, sp.GetService <HistoricInstanceConverter>(), sp.GetService <ILoggerFactory>())); }); services.AddScoped <SecurityPoliciesApplicationService>(); services .AddTransient <PageRetriever>() .AddTransient <ProcessDefinitionConverter>() .AddTransient <ProcessDefinitionSortApplier>() .AddTransient <ProcessDefinitionResourceAssembler>() .AddTransient <ProcessDefinitionMetaResourceAssembler>() .AddTransient <DeploymentConverter>() .AddTransient <DeploymentSortApplier>() .AddTransient <PageableProcessDefinitionRepositoryService>() .AddTransient <PageableDeploymentRespositoryService>(); services.AddTransient <TaskVariableResourceAssembler>(); services.AddTransient <TaskResourceAssembler>(); services.AddTransient <ProcessInstanceVariableResourceAssembler>(); services.AddTransient <AuthenticationWrapper>(); services.AddTransient <IMvcControllerDiscovery, MvcControllerDiscovery>(); mvcBuilder.AddApplicationPart(typeof(ProcessEngineRestExtention).Assembly); return(mvcBuilder); }
public IonOutputFormater(JsonOutputFormatter jsonOutputFormatter) { this.jsonOutputFormatter = jsonOutputFormatter; SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/ion+json")); SupportedEncodings.Add(Encoding.UTF8); }
public ExceptionMiddleware(RequestDelegate next, JsonOutputFormatter outputFormatter, IHttpResponseStreamWriterFactory streamWriterFactory) { _next = next; _outputFormatter = outputFormatter; _streamWriterFactory = streamWriterFactory; }
// This method gets called by a runtime. // Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { services.AddLogging(); services.Configure<MvcOptions>(options => { var settings = new JsonSerializerSettings() { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore, ContractResolver = new CamelCaseExceptDictionaryKeysResolver() }; options.InputFormatters.Clear(); options.OutputFormatters.Clear(); var inputFormatter = new JsonInputFormatter(settings); var outputFormatter = new JsonOutputFormatter(settings); options.InputFormatters.Insert(0, inputFormatter); options.OutputFormatters.Insert(0, outputFormatter); options.ModelBinders.Add(new UserPrincipleModelBinder()); options.Filters.Add(new AuthenticationFilterAttribute() { DataProvider = DataAccessControllerFactory.Provider }); options.Filters.Add(new HandleFinalErrorFilterAttribute()); }); services.AddSingleton<IControllerFactory, DataAccessControllerFactory>(); services.AddMvc(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowAllOrigins", builder => { builder.AllowCredentials(); builder.AllowAnyOrigin(); builder.AllowAnyHeader(); builder.AllowAnyMethod(); builder.Build(); }); }); services.AddEntityFramework() .AddInMemoryDatabase() .AddDbContext<ApplicationDbContext<ApplicationUser, Application, IdentityRole, string>>(options => { options.UseInMemoryDatabase(); }); services.AddScoped<IAuthStore<ApplicationUser, Application>, AuthStore<ApplicationUser, Application, IdentityRole, ApplicationDbContext<ApplicationUser, Application, IdentityRole, string>, string>>(); services.AddScoped<AuthManager<ApplicationUser, Application>>(); //var i = new MockUnitOfWork<string, ApplicationDbContext<ApplicationUser, Application, IdentityRole, string>>(null); //IUnitOfWork services.AddScoped<IUnitOfWork<string>, MockUnitOfWork<string, ApplicationDbContext<ApplicationUser, Application, IdentityRole, string>>>(); services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.Password = new PasswordOptions() { RequiredLength = 1, RequireDigit = false, RequireLowercase = false, RequireUppercase = false, RequireNonLetterOrDigit = false }; }).AddEntityFrameworkStores<ApplicationDbContext<ApplicationUser, Application, IdentityRole, string>>().AddDefaultTokenProviders(); services.AddAuthentication(); services.AddAuthorization(options => options.AddPolicy("ElevatedRights", policy => policy.RequireRole("Admin", "PowerUser", "BackupAdministrator").Build())); // Add framework services. services.AddInstance<IConfiguration>(Configuration); services.AddCaching(); services.AddSignalR(); services.AddMvc(options => { // for CEf client var jsonOutputFormatter = new JsonOutputFormatter(); jsonOutputFormatter.SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects; var jsonInputFormatter = new JsonInputFormatter(); jsonInputFormatter.SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects; options.OutputFormatters.Insert(0, jsonOutputFormatter); options.InputFormatters.Insert(0, jsonInputFormatter); }); }
/// <summary> /// Initializes a new instance of <see cref="JsonHelper"/> that is backed by <paramref name="jsonOutputFormatter"/>. /// </summary> /// <param name="jsonOutputFormatter">The <see cref="JsonOutputFormatter"/> used to serialize JSON.</param> public JsonHelper([NotNull] JsonOutputFormatter jsonOutputFormatter) { _jsonOutputFormatter = jsonOutputFormatter; }
public BeerController(IBeerDbContext beerDbContext, JsonOutputFormatter outputFormatter) { this.beerDbContext = beerDbContext; }
public JsonFormatterController(ArrayPool <char> charPool) { _indentingFormatter = new JsonOutputFormatter(_indentedSettings, charPool); }
public IServiceProvider ConfigureServices(IServiceCollection services) { try { services.AddMvc() .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <Startup>()) .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); }); services.Configure <MvcOptions>(opts => { var formatter = opts.OutputFormatters.FirstOrDefault(i => i.GetType() == typeof(JsonOutputFormatter)); var jsonFormatter = formatter as JsonOutputFormatter; var formatterSettings = jsonFormatter == null ? JsonSerializerSettingsProvider.CreateSerializerSettings() : jsonFormatter.PublicSerializerSettings; if (formatter != null) { opts.OutputFormatters.RemoveType <JsonOutputFormatter>(); } formatterSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ss.fffZ"; JsonOutputFormatter jsonOutputFormatter = new JsonOutputFormatter(formatterSettings, ArrayPool <char> .Create()); opts.OutputFormatters.Insert(0, jsonOutputFormatter); }); services.AddSwaggerGen(options => { options.DefaultLykkeConfiguration(ApiVersion, ApiTitle); options.OperationFilter <ApiKeyHeaderOperationFilter>(); options.OperationFilter <ObsoleteOperationFilter>(); options.DocumentFilter <SecurityRequirementsDocumentFilter>(); options.AddSecurityDefinition("oauth2", new OAuth2Scheme { Type = "oauth2", Flow = "implicit", AuthorizationUrl = _appSettings.CurrentValue.SwaggerSettings.Security.AuthorizeEndpoint }); }); services.AddAuthentication(OAuth2IntrospectionDefaults.AuthenticationScheme) .AddOAuth2Introspection(options => { options.Authority = _appSettings.CurrentValue.WalletApiv2.OAuthSettings.Authority; options.ClientId = _appSettings.CurrentValue.WalletApiv2.OAuthSettings.ClientId; options.ClientSecret = _appSettings.CurrentValue.WalletApiv2.OAuthSettings.ClientSecret; options.NameClaimType = JwtClaimTypes.Subject; options.EnableCaching = true; options.CacheDuration = TimeSpan.FromMinutes(1); options.SkipTokensWithDots = true; }).CustomizeServerAuthentication(); services.Configure <ApiBehaviorOptions>(options => { // Wrap failed model state into LykkeApiErrorResponse. options.InvalidModelStateResponseFactory = InvalidModelStateResponseFactory.CreateInvalidModelResponse; }); var builder = new ContainerBuilder(); Log = CreateLogWithSlack(services, _appSettings); builder.Populate(services); builder.RegisterModule(new Api2Module(_appSettings, Log)); builder.RegisterModule(new ClientsModule(_appSettings, Log)); builder.RegisterModule(new AspNetCoreModule()); builder.RegisterModule(new CqrsModule(_appSettings.CurrentValue, Log)); builder.RegisterModule(new RepositoriesModule(_appSettings.Nested(x => x.WalletApiv2.Db), Log)); ApplicationContainer = builder.Build(); return(new AutofacServiceProvider(ApplicationContainer)); } catch (Exception ex) { Log?.WriteFatalError(nameof(Startup), nameof(ConfigureServices), ex); throw; } }
public IServiceProvider ConfigureServices(IServiceCollection services) { var settingsManager = Configuration.LoadSettings <AppSettings>(options => { options.SetConnString(x => x.SlackNotifications.AzureQueue.ConnectionString); options.SetQueueName(x => x.SlackNotifications.AzureQueue.QueueName); options.SenderName = $"{AppEnvironment.Name} {AppEnvironment.Version}"; }); #if !DEBUG services.AddApplicationInsightsTelemetry(); #endif var mappingConfig = new MapperConfiguration(mc => { mc.AddProfile(new AutoMapperProfile(settingsManager.CurrentValue.PartnerApiService .MoneyDecimalPointStringPrecision)); }); services.AddSingleton(mappingConfig.CreateMapper()); services.AddMvc() .SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddMvcOptions(opt => { opt.Filters.Add(typeof(MaintenanceFilter)); opt.Filters.Add(typeof(NoContentFilter)); }) .AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); }) .AddFluentValidation(opt => { opt.RegisterValidatorsFromAssembly(Assembly.GetEntryAssembly()); }); services.Configure <MvcOptions>(opts => { var formatter = opts.OutputFormatters.FirstOrDefault(i => i.GetType() == typeof(JsonOutputFormatter)); var jsonFormatter = formatter as JsonOutputFormatter; var formatterSettings = jsonFormatter == null ? JsonSerializerSettingsProvider.CreateSerializerSettings() : jsonFormatter.PublicSerializerSettings; if (formatter != null) { opts.OutputFormatters.RemoveType <JsonOutputFormatter>(); } formatterSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ss.fffZ"; var jsonOutputFormatter = new JsonOutputFormatter(formatterSettings, ArrayPool <char> .Create()); opts.OutputFormatters.Insert(0, jsonOutputFormatter); }); _appSettings = settingsManager.CurrentValue; services.AddSwaggerGen(options => { options.DefaultLykkeConfiguration(ApiVersion, ApiTitle); options.OperationFilter <ApiKeyHeaderOperationFilter>(); }); services.Configure <ApiBehaviorOptions>(options => { // Wrap failed model state into LykkeApiErrorResponse. //options.InvalidModelStateResponseFactory = InvalidModelStateResponseFactory.CreateInvalidModelResponse; }); services.AddLykkeLogging( settingsManager.ConnectionString(s => s.PartnerApiService.Db.LogsConnString), "PartnerApiServiceLogs", _appSettings.SlackNotifications.AzureQueue.ConnectionString, _appSettings.SlackNotifications.AzureQueue.QueueName); var builder = new ContainerBuilder(); builder.Populate(services); builder.RegisterModule(new AutofacModule(settingsManager)); ApplicationContainer = builder.Build(); InvalidModelStateResponseFactory.Logger = ApplicationContainer.Resolve <ILogFactory>() .CreateLog(nameof(InvalidModelStateResponseFactory)); return(new AutofacServiceProvider(ApplicationContainer)); }
public IonOutputFormatter(JsonOutputFormatter jsonOutputFormatter) { _jsonOutputFormatter = jsonOutputFormatter ?? throw new ArgumentNullException(nameof(jsonOutputFormatter)); SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/ion+json")); SupportedEncodings.Add(Encoding.UTF8); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Use an in-memory database for qucik dev and testing // Use real database in production // Note that because we use in memory database, any data will be lost when the applcaition closes. So we have load test data in startup services.AddDbContext <HotelApiContext>(opt => opt.UseInMemoryDatabase()); /* * The ConfigureServices method is: * 1. Optional. * 2. Called by the web host before the Configure method to configure the app's services. * * The Configure method is used to specify how the app responds to HTTP requests. The request pipeline is configured by adding middleware components to an IApplicationBuilder instance. * IApplicationBuilder is available to the Configure method, but it isn't registered in the service container. */ if (HostingEnvironment.IsDevelopment()) { // Development configuration } else { // Staging/Production configuration } // Add framework services services.AddMvc(opt => { // Add JsonExceptionFilter to filters opt.Filters.Add(typeof(JsonExceptionFilter)); // Require HTTPS for all controllers. Redirects clients to encrypted HTTPS connecitons opt.SslPort = _httpPort; opt.Filters.Add(typeof(RequireHttpsAttribute)); // OutputFormatters contains all the classes that can format the output of a response like json or text output formatter // Grabing a refrence to json output formatter. SIngle makes sure one and only one json formatter is returned. JsonOutputFormatter jsonFormatter = opt.OutputFormatters.OfType <JsonOutputFormatter>().Single(); // Removing the old Json outputformmater. opt.OutputFormatters.Remove(jsonFormatter); // Adding an instance of our ion output by passing a refrence to json formmater that was retrived from the list opt.OutputFormatters.Add(new IonOutputFormatter(jsonFormatter)); // With the above configuration we would see << Content-Type →application/ion+json; charset=utf-8 >> in our response. }); // using lowerclasses services.AddRouting(opt => opt.LowercaseUrls = true); services.AddApiVersioning(opt => { // Using Mediatype versioning opt.ApiVersionReader = new MediaTypeApiVersionReader(); opt.AssumeDefaultVersionWhenUnspecified = true; // Assumes the default version if no other version is specified. opt.ReportApiVersions = true; // Make version reported in header responce. opt.DefaultApiVersion = new Microsoft.AspNetCore.Mvc.ApiVersion(1, 0); // Default API version is set to 1.0 opt.ApiVersionSelector = new CurrentImplementationApiVersionSelector(opt); // Now you can use ApiVersion("1.0") attribute for each controller }); // This line pull the properties form the info section of the appSettings.json and then creates a new instance of Hotelinfo from those values // Then it wraps the HotelInfo instance in an interface called IOptions and puts that into service container. // Once it's in service container it can be injected into contrllers. services.Configure <HotelInfo>(Configuration.GetSection("Info")); }
public ItemsDatasourceTagHelper(JsonOutputFormatter jsonFormatter) { _jsonFormatter = jsonFormatter; }
public void OutputFormatters_InstancesOf_ReturnsNonEmptyCollectionIfSomeExist() { // Arrange var formatters = new MvcOptions().OutputFormatters; formatters.Add(typeof(JsonOutputFormatter)); var formatter1 = new JsonOutputFormatter(); var formatter2 = Mock.Of<IOutputFormatter>(); var formatter3 = new JsonOutputFormatter(); var formatter4 = Mock.Of<IOutputFormatter>(); formatters.Add(formatter1); formatters.Add(formatter2); formatters.Add(formatter3); formatters.Add(formatter4); var expectedFormatters = new List<JsonOutputFormatter> { formatter1, formatter3 }; // Act var jsonFormatters = formatters.InstancesOf<JsonOutputFormatter>().ToList(); // Assert Assert.NotEmpty(jsonFormatters); Assert.Equal(jsonFormatters, expectedFormatters); }
public FallbackOnTypeBasedMatchController(IOptions <MvcOptions> mvcOptions) { _mvcOptions = mvcOptions; _jsonOutputFormatter = mvcOptions.Value.OutputFormatters.OfType <JsonOutputFormatter>().First(); }
public async Task WriteToStreamAsync_UsesCorrectCharacterEncoding( string content, string encodingAsString, bool isDefaultEncoding) { // Arrange var formatter = new JsonOutputFormatter(); var formattedContent = "\"" + content + "\""; var mediaType = string.Format("application/json; charset={0}", encodingAsString); var encoding = CreateOrGetSupportedEncoding(formatter, encodingAsString, isDefaultEncoding); var expectedData = encoding.GetBytes(formattedContent); var body = new MemoryStream(); var actionContext = GetActionContext(MediaTypeHeaderValue.Parse(mediaType), body); var outputFormatterContext = new OutputFormatterContext { Object = content, DeclaredType = typeof(string), HttpContext = actionContext.HttpContext, SelectedEncoding = encoding }; // Act await formatter.WriteResponseBodyAsync(outputFormatterContext); // Assert var actualData = body.ToArray(); Assert.Equal(expectedData, actualData); }
public void ConfigureServices(IServiceCollection services) { services.AddEntityFramework() .AddSqlServer() .AddDbContext<BookingDbContext>(options => options.UseSqlServer(Configuration.GetSection("Database:Connection").Value)); services.Configure<AuthOptions>(options => { options.DefaultUsername = Configuration.GetSection("DefaultUser:Username").Value; options.DefaultPassword = Configuration.GetSection("DefaultUSer:Password").Value; }); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<BookingDbContext>() .AddDefaultTokenProviders(); services.AddMvc(); services.Configure<MvcOptions>(options => { //options.Filters.Add(new AuthorizeAttribute()); var jsonOutputFormatter = new JsonOutputFormatter { SerializerSettings = JsonExtensions.JsonSerializerSettings() }; options.OutputFormatters.Insert(0, jsonOutputFormatter); }); // Configure Auth services.Configure<AuthorizationOptions>(options => { options.AddPolicy(AppPolicies.AccessAdminArea.ToString(), new AuthorizationPolicyBuilder().RequireClaim(AppPolicies.AccessAdminArea.ToString(), "Allowed").Build()); }); // TODO refactor IoC registration DataAccess.IocRegistrations.RegisterServices(services); Business.IocRegistrations.RegisterServices(services); // TODO refactor Automapper configuration Business.AutoMapperConfiguration.Configure(); }
public async Task WriteToStreamAsync_UsesCorrectCharacterEncoding( string content, string encodingAsString, bool isDefaultEncoding) { // Arrange var formatter = new JsonOutputFormatter(); var formattedContent = "\"" + content + "\""; var mediaType = string.Format("application/json; charset={0}", encodingAsString); var encoding = CreateOrGetSupportedEncoding(formatter, encodingAsString, isDefaultEncoding); var preamble = encoding.GetPreamble(); var data = encoding.GetBytes(formattedContent); var expectedData = new byte[preamble.Length + data.Length]; Buffer.BlockCopy(preamble, 0, expectedData, 0, preamble.Length); Buffer.BlockCopy(data, 0, expectedData, preamble.Length, data.Length); var memStream = new MemoryStream(); var outputFormatterContext = new OutputFormatterContext { Object = content, DeclaredType = typeof(string), ActionContext = GetActionContext(MediaTypeHeaderValue.Parse(mediaType), memStream), SelectedEncoding = encoding }; // Act await formatter.WriteResponseBodyAsync(outputFormatterContext); // Assert var actualData = memStream.ToArray(); Assert.Equal(expectedData, actualData); }
/// <inheritdoc /> public HtmlString Serialize(object value, [NotNull] JsonSerializerSettings serializerSettings) { var jsonOutputFormatter = new JsonOutputFormatter(serializerSettings); return(SerializeInternal(jsonOutputFormatter, value)); }
public void OutputFormatters_InstanceOfOrDefault_ReturnsInstanceOfIOutputFormatterIfOneExists() { // Arrange var formatters = new MvcOptions().OutputFormatters; formatters.Add(Mock.Of<IOutputFormatter>()); formatters.Add(typeof(JsonOutputFormatter)); var jsonFormatter = new JsonOutputFormatter(); formatters.Add(jsonFormatter); // Act var formatter = formatters.InstanceOfOrDefault<JsonOutputFormatter>(); // Assert Assert.NotNull(formatter); Assert.IsType<JsonOutputFormatter>(formatter); Assert.Same(jsonFormatter, formatter); }
public static bool RemoveJsonOutputFormatter(this MvcOptions options, out JsonOutputFormatter formatter) { formatter = options.OutputFormatters.OfType <JsonOutputFormatter>().Single(); return(options.OutputFormatters.Remove(formatter)); }
public async Task WriteToStreamAsync_RoundTripsJToken() { // Arrange var beforeMessage = "Hello World"; var formatter = new JsonOutputFormatter(); var before = new JValue(beforeMessage); var memStream = new MemoryStream(); var outputFormatterContext = GetOutputFormatterContext( beforeMessage, typeof(string), "application/json; charset=utf-8", memStream); // Act await formatter.WriteResponseBodyAsync(outputFormatterContext); // Assert memStream.Position = 0; var after = JToken.Load(new JsonTextReader(new StreamReader(memStream))); var afterMessage = after.ToObject<string>(); Assert.Equal(beforeMessage, afterMessage); }
/// <summary> /// 注册Workflow Rest服务 /// </summary> /// <param name="mvcBuilder"></param> /// <param name="config"></param> /// <returns></returns> public static IMvcBuilder AddProcessEngineRestServices(this IMvcBuilder mvcBuilder, IConfiguration config) { IServiceCollection services = mvcBuilder.Services; mvcBuilder.AddMvcOptions(opts => { JsonOutputFormatter jsonFormatter = opts.OutputFormatters.FirstOrDefault(x => x.GetType() == typeof(JsonOutputFormatter)) as JsonOutputFormatter; if (jsonFormatter != null) { //jsonFormatter.PublicSerializerSettings.TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple; //jsonFormatter.PublicSerializerSettings.TypeNameHandling = TypeNameHandling.All; jsonFormatter.PublicSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; } opts.ModelBinderProviders.Insert(0, new PageableModelBinderProvider()); }); services.AddTransient <ProcessInstanceSortApplier>(); services.AddSingleton <PageRetriever>(); services.AddTransient <HistoricInstanceConverter>(); services.AddTransient <HistoryInstanceSortApplier>(); services.AddTransient <PageableProcessHistoryRepositoryService>(sp => { return(new PageableProcessHistoryRepositoryService( sp.GetService <PageRetriever>(), sp.GetService <IProcessEngine>().HistoryService, sp.GetService <HistoryInstanceSortApplier>(), sp.GetService <HistoricInstanceConverter>(), sp.GetService <SecurityPoliciesApplicationService>(), sp.GetService <ILoggerFactory>() )); }); services.AddTransient <PageableProcessInstanceRepositoryService>(sp => { IProcessEngine engine = sp.GetService <IProcessEngine>(); return(new PageableProcessInstanceRepositoryService(sp.GetService <PageRetriever>(), engine.RuntimeService, sp.GetService <ProcessInstanceSortApplier>(), sp.GetService <ProcessInstanceConverter>(), sp.GetService <ILoggerFactory>())); }); services.AddTransient <ListConverter>(); services.AddTransient <TaskConverter>(sp => new TaskConverter(sp.GetService <ListConverter>())); services.AddTransient <HistoricTaskInstanceConverter>(sp => new HistoricTaskInstanceConverter(sp.GetService <ListConverter>())); services.AddTransient <TaskSortApplier>(); services.AddTransient <HistoryTaskSortApplier>(); //services.AddTransient<MessageProducerActivitiEventListener>(); services.AddTransient <PageableTaskRepositoryService>(sp => { IProcessEngine engine = sp.GetService <IProcessEngine>(); return(new PageableTaskRepositoryService( engine.TaskService, sp.GetService <TaskConverter>(), sp.GetService <HistoricTaskInstanceConverter>(), sp.GetService <IHistoryService>(), sp.GetService <PageRetriever>(), sp.GetService <TaskSortApplier>(), sp.GetService <HistoryTaskSortApplier>())); }); services.AddTransient <ProcessInstanceConverter>(sp => { IProcessEngine engine = sp.GetService <IProcessEngine>(); return(new ProcessInstanceConverter(sp.GetService <ListConverter>())); }); services.AddTransient <ProcessInstanceResourceAssembler>(); services.AddScoped <ProcessEngineWrapper>(sp => { IProcessEngine engine = sp.GetService <IProcessEngine>(); IHttpContextAccessor httpContext = sp.GetService <IHttpContextAccessor>(); return(new ProcessEngineWrapper(sp.GetService <ProcessInstanceConverter>(), sp.GetService <PageableProcessInstanceRepositoryService>(), sp.GetService <TaskConverter>(), sp.GetService <PageableTaskRepositoryService>(), null, sp.GetService <SecurityPoliciesApplicationService>(), null, null, engine, sp.GetService <HistoricInstanceConverter>(), sp.GetService <ILoggerFactory>())); }); services.AddScoped <SecurityPoliciesApplicationService>(); services .AddTransient <PageRetriever>() .AddTransient <ProcessDefinitionConverter>() .AddTransient <ProcessDefinitionSortApplier>() .AddTransient <ProcessDefinitionResourceAssembler>() .AddTransient <ProcessDefinitionMetaResourceAssembler>() .AddTransient <DeploymentConverter>() .AddTransient <DeploymentSortApplier>() .AddTransient <PageableProcessDefinitionRepositoryService>() .AddTransient <PageableDeploymentRespositoryService>(); services.AddTransient <TaskVariableResourceAssembler>(); services.AddTransient <TaskResourceAssembler>(); services.AddTransient <ProcessInstanceVariableResourceAssembler>(); services.AddTransient <AuthenticationWrapper>(); services.AddTransient <IMvcControllerDiscovery, MvcControllerDiscovery>(); mvcBuilder.AddApplicationPart(typeof(ProcessEngineRestExtention).Assembly); return(mvcBuilder); }
public static IMvcBuilder AddApiExtensions(this IMvcBuilder builder, IConfigurationSection config = null, Action <ApiExtensionOptions> build = null) { var apiOptions = new ApiExtensionOptions(); #region Include services needed for building uri's in the paging object builder.Services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>(); builder.Services.TryAddSingleton <IActionContextAccessor, ActionContextAccessor>(); builder.Services.AddScoped <IUrlHelper>(x => { var actionContext = x.GetService <IActionContextAccessor>().ActionContext; return(new UrlHelper(actionContext)); }); builder.Services.AddScoped <ILinkProvider, LinkProvider>(); #endregion #region Register Options if (config != null && build != null) { builder.Services.Configure <ApiExtensionOptions>(x => { }); } if (config != null) { builder.Services.Configure <ApiExtensionOptions>(config); config.Bind(apiOptions); } if (build != null) { builder.Services.Configure <ApiExtensionOptions>(build); build(apiOptions); } #endregion #region Configuration from options if (!apiOptions.DisableVersioning) { builder.AddMvcOptions(options => { options.Conventions.Insert(0, new RouteConvention(new RouteAttribute("{apiVersion}"))); }); builder.Services.ConfigureSwaggerGen(options => { options.DocInclusionPredicate((version, apiDescription) => { var allowedVersions = apiDescription.ActionAttributes().OfType <VersionsAttribute>().FirstOrDefault(); return(allowedVersions != null && allowedVersions.AcceptedVersions.Contains(version)); }); }); } #endregion builder.AddMvcOptions(options => { options.Filters.Insert(0, new ConsumesAttribute("application/json")); options.Filters.Insert(1, new ProducesAttribute("application/json")); options.ModelBinderProviders.Insert(0, new CommaDelimitedArrayModelBinderProvider()); JsonOutputFormatter jsonFormatter = options.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault(); jsonFormatter?.SupportedMediaTypes.Add("application/hal+json"); }); builder.AddJsonOptions(x => { x.SerializerSettings.Initialize(); }); return(builder); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc( setupAction => { setupAction.ReturnHttpNotAcceptable = true; setupAction.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); var xmlDataContractSerializerInputFormatter = new XmlDataContractSerializerInputFormatter(); xmlDataContractSerializerInputFormatter.SupportedMediaTypes.Add(AcceptMediaTypes.MarvinHateoasWithAuthorFullPlusXml); setupAction.InputFormatters.Add(xmlDataContractSerializerInputFormatter); JsonOutputFormatter jsonOutputFormatter = setupAction.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault(); if (jsonOutputFormatter != null) { jsonOutputFormatter.SupportedMediaTypes.Add(AcceptMediaTypes.MarvinHateoasPlusJson); jsonOutputFormatter.SupportedMediaTypes.Add(AcceptMediaTypes.MarvinHateoasWithAuthorFullPlusJson); jsonOutputFormatter.SupportedMediaTypes.Add(AcceptMediaTypes.MarvinHateoasWithDateOfDeathPlusJson); } }).AddJsonOptions( options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }); // register the DbContext on the container, getting the connection string from // appSettings (note: use this during development; in a production environment, // it's better to store the connection string in an environment variable) string connectionString = Startup.Configuration["connectionStrings:libraryDBConnectionString"]; services.AddDbContext <LibraryContext>(o => o.UseSqlServer(connectionString)); // register the repository services.AddScoped <ILibraryRepository, LibraryRepository>(); services.AddSingleton <IActionContextAccessor, ActionContextAccessor>(); services.AddScoped <IUrlHelper, UrlHelper>( implementationFactory => { ActionContext actionContext = implementationFactory.GetService <IActionContextAccessor>().ActionContext; return(new UrlHelper(actionContext)); }); services.AddTransient <IPropertyMappingService, PropertyMappingService>(); services.AddTransient <ITypeHelperService, TypeHelperService>(); services.AddHttpCacheHeaders( (expirationModelOptions) => { expirationModelOptions.MaxAge = 600; }, (validationModelOptions) => { validationModelOptions.MustRevalidate = true; }); services.AddResponseCaching(); services.AddMemoryCache(); services.Configure <IpRateLimitOptions>( (options) => { options.GeneralRules = new List <RateLimitRule> { new RateLimitRule { Endpoint = "*", Limit = 3, Period = "5m" } }; }); services.AddSingleton <IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>(); services.AddSingleton <IIpPolicyStore, MemoryCacheIpPolicyStore>(); }
public async Task ObjectResult_Execute_CallsJsonResult_SetsContent() { // Arrange var expectedContentType = "application/json; charset=utf-8"; var nonStringValue = new { x1 = 10, y1 = "Hello" }; var httpResponse = Mock.Of<HttpResponse>(); httpResponse.Body = new MemoryStream(); var actionContext = CreateMockActionContext(httpResponse); var tempStream = new MemoryStream(); var tempHttpContext = new Mock<HttpContext>(); var tempHttpResponse = new Mock<HttpResponse>(); tempHttpResponse.SetupGet(o => o.Body).Returns(tempStream); tempHttpResponse.SetupProperty<string>(o => o.ContentType); tempHttpContext.SetupGet(o => o.Request).Returns(new DefaultHttpContext().Request); tempHttpContext.SetupGet(o => o.Response).Returns(tempHttpResponse.Object); var tempActionContext = new ActionContext(tempHttpContext.Object, new RouteData(), new ActionDescriptor()); var formatterContext = new OutputFormatterContext() { HttpContext = tempActionContext.HttpContext, Object = nonStringValue, DeclaredType = nonStringValue.GetType() }; var formatter = new JsonOutputFormatter(); formatter.WriteResponseHeaders(formatterContext); await formatter.WriteAsync(formatterContext); // Act var result = new ObjectResult(nonStringValue); await result.ExecuteResultAsync(actionContext); // Assert Assert.Equal(expectedContentType, httpResponse.ContentType); Assert.Equal(tempStream.ToArray(), ((MemoryStream)actionContext.HttpContext.Response.Body).ToArray()); }