public static IMvcCoreBuilder AddWebApiProxy(this IMvcCoreBuilder mvcBuilder, Action <WebApiProxyOptions> optionAction) { var option = new WebApiProxyOptions(); optionAction(option); foreach (var o in option.WebApiProxies) { var interfaceTypes = o.GetType().Assembly.GetTypes() .Where(x => x.IsInterface && x.GetMethods() .SelectMany(m => m.GetCustomAttributes(typeof(ApiActionAttribute), true)).Any()); foreach (var t in interfaceTypes) { mvcBuilder.AddMvcOptions(opt => { opt.Conventions.Add(new ControllerModelConvention(t)); opt.Conventions.Add(new ActionModelConvention(t)); opt.Conventions.Add(new ParameterModelConvention(t)); }); } mvcBuilder.ConfigureApplicationPartManager(manager => { var featureProvider = new ServiceControllerFeatureProvider(interfaceTypes); manager.FeatureProviders.Remove( manager.FeatureProviders.FirstOrDefault(x => x.GetType() == typeof(ControllerFeatureProvider))); manager.FeatureProviders.Add(featureProvider); }); ; } return(mvcBuilder); }
public static IMvcCoreBuilder AddHybridModelBinder(this IMvcCoreBuilder builder) { builder = builder ?? throw new ArgumentNullException(nameof(builder)); return(builder.AddMvcOptions(mvcOptions => mvcOptions .AddHybridModelBinder(builder.Services))); }
/// <summary> /// Adds Fluent Validation services to the specified /// <see cref="T:Microsoft.Extensions.DependencyInjection.IMvcBuilder" />. /// </summary> /// <returns> /// An <see cref="T:Microsoft.Extensions.DependencyInjection.IMvcCoreBuilder" /> that can be used to further configure the /// MVC services. /// </returns> public static IMvcCoreBuilder AddFluentValidation(this IMvcCoreBuilder mvcBuilder, Action <FluentValidationMvcConfiguration> configurationExpression = null) { var expr = configurationExpression ?? delegate { }; var config = new FluentValidationMvcConfiguration(); expr(config); if (config.AssembliesToRegister.Count > 0) { RegisterTypes(config.AssembliesToRegister, mvcBuilder.Services); } RegisterServices(mvcBuilder.Services, config); // clear all model validation providers since fluent validation will be handling everything #pragma warning disable CS0612 // Type or member is obsolete if (config.ClearValidatorProviders) { #pragma warning restore CS0612 // Type or member is obsolete mvcBuilder.AddMvcOptions( options => { options.ModelValidatorProviders.Clear(); }); } return(mvcBuilder); }
/// <summary> /// Use feature folders with custom options /// </summary> public static IMvcCoreBuilder AddFeatureFolders(this IMvcCoreBuilder services, FeatureFolderOptions options) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (options == null) { throw new ArgumentException(nameof(options)); } var expander = new FeatureViewLocationExpander(options); services.AddMvcOptions(o => o.Conventions.Add(new FeatureControllerModelConvention(options))) .AddRazorViewEngine(o => { // o.ViewLocationFormats.Clear(); o.ViewLocationFormats.Add(options.FeatureNamePlaceholder + @"\{0}.cshtml"); o.ViewLocationFormats.Add(options.FeatureFolderName + @"\Shared\{0}.cshtml"); o.ViewLocationFormats.Add(options.DefaultViewLocation); o.ViewLocationExpanders.Add(expander); }); return(services); }
/// <summary> /// Adds Fluent Validation services to the specified /// <see cref="T:Microsoft.Extensions.DependencyInjection.IMvcBuilder" />. /// </summary> /// <returns> /// An <see cref="T:Microsoft.Extensions.DependencyInjection.IMvcCoreBuilder" /> that can be used to further configure the /// MVC services. /// </returns> public static IMvcCoreBuilder AddFluentValidation(this IMvcCoreBuilder mvcBuilder, Action <FluentValidationMvcConfiguration> configurationExpression = null) { var config = new FluentValidationMvcConfiguration(ValidatorOptions.Global); configurationExpression?.Invoke(config); mvcBuilder.Services.AddValidatorsFromAssemblies(config.AssembliesToRegister); RegisterServices(mvcBuilder.Services, config); mvcBuilder.AddMvcOptions(options => { // Check if the providers have already been added. // We shouldn't have to do this, but there's a bug in the ASP.NET Core integration // testing components that can cause Configureservices to be called multple times // meaning we end up with duplicates. if (!options.ModelMetadataDetailsProviders.Any(x => x is FluentValidationBindingMetadataProvider)) { options.ModelMetadataDetailsProviders.Add(new FluentValidationBindingMetadataProvider()); } if (!options.ModelValidatorProviders.Any(x => x is FluentValidationModelValidatorProvider)) { options.ModelValidatorProviders.Insert(0, new FluentValidationModelValidatorProvider(config.ImplicitlyValidateChildProperties)); } }); return(mvcBuilder); }
public static IMvcCoreBuilder AddWebApiProxyServer(this IMvcCoreBuilder mvcBuilder, Action <WebApiProxyOptions> optionAction) { AppDomain.CurrentDomain.UpdateExcutingAssemblies(); var option = new WebApiProxyOptions(); optionAction(option); foreach (var o in option.WebApiProxies) { var interfaceTypes = o.GetType().Assembly.GetTypes() .Where(x => x.IsInterface); foreach (var t in interfaceTypes) { mvcBuilder.AddMvcOptions(opt => { opt.Conventions.Add(new ControllerModelConvention(t)); opt.Conventions.Add(new ActionModelConvention(t)); opt.Conventions.Add(new ParameterModelConvention(t)); }); } mvcBuilder.ConfigureApplicationPartManager(manager => { var featureProvider = new ServiceControllerFeatureProvider(interfaceTypes); manager.FeatureProviders.Remove( manager.FeatureProviders.FirstOrDefault(x => x.GetType() == typeof(ControllerFeatureProvider))); manager.FeatureProviders.Add(featureProvider); }); ; } return(mvcBuilder); }
public static IMvcCoreBuilder AddCustomMvcOptions( this IMvcCoreBuilder builder, IHostingEnvironment hostingEnvironment) => builder.AddMvcOptions( options => { // Controls how controller actions cache content from the appsettings.json file. var jsonInputFormatterMediaTypes = options .InputFormatters .OfType <JsonInputFormatter>() .First() .SupportedMediaTypes; var jsonOutputFormatterMediaTypes = options .OutputFormatters .OfType <JsonOutputFormatter>() .First() .SupportedMediaTypes; // Add RESTful JSON media type (application/vnd.restful+json) to the JSON input and output formatters. // See http://restfuljson.org/ jsonInputFormatterMediaTypes.Insert(0, ContentType.RestfulJson); jsonOutputFormatterMediaTypes.Insert(0, ContentType.RestfulJson); // Remove string and stream output formatters. These are not useful for an API serving JSON or XML. options.OutputFormatters.RemoveType <StreamOutputFormatter>(); options.OutputFormatters.RemoveType <StringOutputFormatter>(); // Returns a 406 Not Acceptable if the MIME type in the Accept HTTP header is not valid. options.ReturnHttpNotAcceptable = true; });
public static IMvcCoreBuilder AddCustomMvcOptions( this IMvcCoreBuilder builder, IHostingEnvironment hostingEnvironment) => builder.AddMvcOptions( options => { // Controls how controller actions cache content from the appsettings.json file. var cacheProfileOptions = builder.Services.BuildServiceProvider().GetRequiredService <CacheProfileOptions>(); foreach (var keyValuePair in cacheProfileOptions) { options.CacheProfiles.Add(keyValuePair); } // Add RESTful JSON media type to the JSON input and output formatters. See http://restfuljson.org/ options .InputFormatters .OfType <JsonInputFormatter>() .First() .SupportedMediaTypes .Add("application/vnd.restful+json"); options .OutputFormatters .OfType <JsonOutputFormatter>() .First() .SupportedMediaTypes .Add("application/vnd.restful+json"); // Remove string and stream output formatters. These are not useful for an API serving JSON or XML. options.OutputFormatters.RemoveType <StreamOutputFormatter>(); options.OutputFormatters.RemoveType <StringOutputFormatter>(); // Returns a 406 Not Acceptable if the MIME type in the Accept HTTP header is not valid. options.ReturnHttpNotAcceptable = true; });
public static IMvcCoreBuilder AddCustomMvcOptions( this IMvcCoreBuilder builder, IConfigurationRoot configuration, IHostingEnvironment hostingEnvironment) => builder.AddMvcOptions( options => { // Controls how controller actions cache content from the config.json file. var cacheProfileSettings = configuration.GetSection <CacheProfileSettings>(); foreach (var keyValuePair in cacheProfileSettings.CacheProfiles) { options.CacheProfiles.Add(keyValuePair); } if (hostingEnvironment.IsDevelopment()) { // Lets you pass a format parameter into the query string to set the response type: // e.g. ?format=application/json. Good for debugging. options.Filters.Add(new FormatFilterAttribute()); } // Check model state for null or invalid models and automatically return a 400 Bad Request. options.Filters.Add(new ValidateModelStateAttribute()); // Remove string and stream output formatters. These are not useful for an API serving JSON or XML. options.OutputFormatters.RemoveType <StreamOutputFormatter>(); options.OutputFormatters.RemoveType <StringOutputFormatter>(); // Returns a 406 Not Acceptable if the MIME type in the Accept HTTP header is not valid. options.ReturnHttpNotAcceptable = true; });
/// <summary> /// Configures built-in .NET Core MVC (things like middleware, routing). Most of this configuration can be adjusted for the developers' need. /// Before calling .AddJsonApi(), a developer can register their own implementation of the following services to customize startup: /// <see cref="IResourceGraphBuilder"/>, <see cref="IServiceDiscoveryFacade"/>, <see cref="IJsonApiExceptionFilterProvider"/>, /// <see cref="IJsonApiTypeMatchFilterProvider"/> and <see cref="IJsonApiRoutingConvention"/>. /// </summary> public void ConfigureMvc(Type dbContextType) { RegisterJsonApiStartupServices(); var intermediateProvider = _services.BuildServiceProvider(); _resourceGraphBuilder = intermediateProvider.GetRequiredService <IResourceGraphBuilder>(); _serviceDiscoveryFacade = intermediateProvider.GetRequiredService <IServiceDiscoveryFacade>(); _dbContextType = dbContextType; AddResourceTypesFromDbContext(intermediateProvider); var exceptionFilterProvider = intermediateProvider.GetRequiredService <IJsonApiExceptionFilterProvider>(); var typeMatchFilterProvider = intermediateProvider.GetRequiredService <IJsonApiTypeMatchFilterProvider>(); var routingConvention = intermediateProvider.GetRequiredService <IJsonApiRoutingConvention>(); _mvcBuilder.AddMvcOptions(options => { options.EnableEndpointRouting = true; options.Filters.Add(exceptionFilterProvider.Get()); options.Filters.Add(typeMatchFilterProvider.Get()); options.Filters.Add(new ConvertEmptyActionResultFilter()); options.InputFormatters.Insert(0, new JsonApiInputFormatter()); options.OutputFormatters.Insert(0, new JsonApiOutputFormatter()); options.Conventions.Insert(0, routingConvention); }); if (_options.ValidateModelState) { _mvcBuilder.AddDataAnnotations(); } _services.AddSingleton <IControllerResourceMapping>(routingConvention); }
public static IMvcCoreBuilder AddCsvSerializerFormatters ( this IMvcCoreBuilder builder , CsvFormatterOptions csvFormatterOptions ) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder .AddFormatterMappings ( (m) => { m .SetMediaTypeMappingForFormat ( "csv" , new MediaTypeHeaderValue("text/csv") ); } ); if (csvFormatterOptions == null) { csvFormatterOptions = new CsvFormatterOptions(); } if (string.IsNullOrWhiteSpace(csvFormatterOptions.CsvColumnsDelimiter)) { throw new ArgumentException ( "CsvDelimiter cannot be empty" ); } //builder.AddMvcOptions(options => options.InputFormatters.Add(new CsvInputFormatter(csvFormatterOptions))); builder .AddMvcOptions ( (options) => { options .OutputFormatters .Add ( new CsvOutputFormatter() ); } ); return (builder); }
public static IMvcCoreBuilder AddHybridModelBinder(this IMvcCoreBuilder builder, Action <HybridModelBinderOptions> setupAction) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } return(builder.AddMvcOptions(mvcOptions => mvcOptions.AddHybridModelBinder(builder.Services, setupAction))); }
/// <summary> /// Adds the <see cref="ProtobufNetInputFormatter"/> and <see cref="ProtobufNetOutputFormatter"/> to the known formatters. /// Also registers the Protobuf-net media header to map to these formatters. /// </summary> /// <param name="builder">Builder to chain off.</param> /// <returns>The fluent <see cref="IMvcCoreBuilder"/> instance.</returns> public static IMvcCoreBuilder AddProtobufNetFormatters(this IMvcCoreBuilder builder) { //Add the formatters to the options. return(builder.AddMvcOptions(options => { options.InputFormatters.Add(new ProtobufNetInputFormatter()); options.OutputFormatters.Add(new ProtobufNetOutputFormatter()); options.FormatterMappings.SetMediaTypeMappingForFormat("ProtobufNet", MediaTypeHeaderValue.Parse("application/Protobuf-Net")); })); }
public static IMvcCoreBuilder AddCustomMvcOptions(this IMvcCoreBuilder builder) { return(builder.AddMvcOptions( options => { // Remove string and stream output formatter. These are not useful for an API serving JSON or XML. options.OutputFormatters.RemoveType <StreamOutputFormatter>(); options.OutputFormatters.RemoveType <StringOutputFormatter>(); })); }
public static IMvcCoreBuilder AddCustomMvcOptions(this IMvcCoreBuilder builder) { return(builder.AddMvcOptions( options => { options.OutputFormatters.RemoveType <StreamOutputFormatter>(); options.OutputFormatters.RemoveType <StringOutputFormatter>(); options.ReturnHttpNotAcceptable = true; })); }
public static IMvcCoreBuilder AddMvcApiResult(this IMvcCoreBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } return(builder.AddMvcOptions(options => { options.Filters.Add(typeof(ApiResultFilterAttribute)); options.Filters.Add(typeof(ApiExceptionFilterAttribute)); })); }
/// <summary> /// <para> /// Add WebHook configuration and services to the specified <paramref name="builder"/>. /// </para> /// <para> /// '<c>WebHooks:{receiver name}:SecretKey:default</c>' configuration values usually contain secret keys for /// WebHook URIs of the form '<c>https://{host}/api/webhooks/incoming/{receiver name}</c>' (with a /// <c>?code=...</c> query string for some receivers). '<c>WebHooks:{receiver name}:SecretKey:{id}</c>' /// configuration values usually contain secret keys for WebHook URIs of the form /// '<c>https://{host}/api/webhooks/incoming/{receiver name}/{id}</c>'. /// </para> /// </summary> /// <param name="builder">The <see cref="IMvcCoreBuilder" /> to configure.</param> /// <returns>The <paramref name="builder"/>.</returns> public static IMvcCoreBuilder AddWebHooks(this IMvcCoreBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } WebHookServiceCollectionSetup.AddWebHookServices(builder.Services); builder.AddMvcOptions(options => options.EnableGlobalRouting = false); return(builder); }
public static IMvcCoreBuilder AddHybridModelBinder( this IMvcCoreBuilder builder, Action <HybridModelBinderOptions> setupAction) { builder = builder ?? throw new ArgumentNullException(nameof(builder)); builder.Services .Configure(setupAction) .ConfigureOptions <HybridModelBinderSetup>(); return(builder .AddMvcOptions(mvcOptions => mvcOptions.AddHybridModelBinder())); }
public static IMvcCoreBuilder AddCustomMvcOptions( this IMvcCoreBuilder builder, IHostingEnvironment hostingEnvironment) => builder.AddMvcOptions( options => { // Remove string and stream output formatters. These are not useful for an API serving JSON or XML. options.OutputFormatters.RemoveType <StreamOutputFormatter>(); options.OutputFormatters.RemoveType <StringOutputFormatter>(); // Returns a 406 Not Acceptable if the MIME type in the Accept HTTP header is not valid. options.ReturnHttpNotAcceptable = true; });
public static IODataApiBuilder AddODataApi(this IMvcCoreBuilder mvc, bool enableLowerCamelCase = true) { var services = mvc.Services; var modelBuilder = new ODataApiBuilder(services, enableLowerCamelCase); services.AddOData(); services.AddSingleton <IModelMetadataProvider>(modelBuilder); services.TryAddSingleton <IEntityKeyAccossor, DefaultEntityKeyAccessor>(); mvc.AddMvcOptions(options => options.Conventions.Add(new CrudControllerNameConvention(modelBuilder))) .ConfigureApplicationPartManager(p => p.FeatureProviders.Add(new CrudControllerFeatureProvider(modelBuilder))); return(modelBuilder); }
public static IMvcCoreBuilder AddMessagePackFormatters(this IMvcCoreBuilder builder, Action <MessagePackFormatterOptions> messagePackFormatterOptionsConfiguration) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } var messagePackFormatterOptions = new MessagePackFormatterOptions(); messagePackFormatterOptionsConfiguration?.Invoke(messagePackFormatterOptions); messagePackFormatterOptions.Options.WithResolver(messagePackFormatterOptions.FormatterResolver); foreach (var extension in messagePackFormatterOptions.SupportedExtensions) { foreach (var contentType in messagePackFormatterOptions.SupportedContentTypes) { builder.AddFormatterMappings(m => m.SetMediaTypeMappingForFormat(extension, new MediaTypeHeaderValue(contentType))); } } //builder.AddMvcOptions(options => options.InputFormatters.Add(new MessagePackInputFormatter(messagePackFormatterOptions))); //builder.AddMvcOptions(options => options.OutputFormatters.Add(new MessagePackOutputFormatter(messagePackFormatterOptions))); builder.AddMvcOptions(options => { options.InputFormatters.Clear(); options.InputFormatters.Add(new MessagePackInputFormatter(messagePackFormatterOptions)); }); builder.AddMvcOptions(options => { options.OutputFormatters.Clear(); options.OutputFormatters.Add(new MessagePackOutputFormatter(messagePackFormatterOptions)); }); return(builder); }
public static IMvcCoreBuilder AddCustomMvcOptions(this IMvcCoreBuilder builder) => builder.AddMvcOptions( options => { // Controls how controller actions cache content from the appsettings.json file. var cacheProfileOptions = builder.Services.BuildServiceProvider().GetRequiredService <CacheProfileOptions>(); foreach (var keyValuePair in cacheProfileOptions) { options.CacheProfiles.Add(keyValuePair); } // Returns a 406 Not Acceptable if the MIME type in the Accept HTTP header is not valid. options.ReturnHttpNotAcceptable = true; });
public static IMvcCoreBuilder AddProtobufFormatters(this IMvcCoreBuilder builder) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } builder.AddMvcOptions(options => { options.InputFormatters.Add(new ProtobufInputFormatter()); options.OutputFormatters.Add(new ProtobufOutputFormatter()); options.FormatterMappings.SetMediaTypeMappingForFormat("protobuf", MediaTypeHeaderValue.Parse("application/x-protobuf")); }); return(builder); }
/// <summary> /// Adds PineBlog Razor Pages services to the services collection. /// </summary> /// <param name="builder">The Microsoft.Extensions.DependencyInjection.IMvcCoreBuilder.</param> public static IMvcCoreBuilder AddPineBlogRazorPages(this IMvcCoreBuilder builder) { ConfigureServices(builder.Services); builder.AddApplicationPart(typeof(Controllers.FileController).Assembly); builder.AddRazorPages(SetRazorPagesOptions); builder.AddMvcOptions(options => { options.Filters.Add <PineBlogViewDataAsyncPageFilter>(); }); builder.AddFluentValidation(); return(builder); }
public static IServiceCollection AddJsonApi <TContext>( this IServiceCollection services, Action <JsonApiOptions> options, IMvcCoreBuilder mvcBuilder) where TContext : DbContext { var config = new JsonApiOptions(); options(config); config.BuildResourceGraph(builder => builder.AddDbContext <TContext>()); mvcBuilder.AddMvcOptions(opt => AddMvcOptions(opt, config)); AddJsonApiInternals <TContext>(services, config); return(services); }
internal static IMvcCoreBuilder AddHal(this IMvcCoreBuilder @this, JsonSerializerSettings serializerSettings) { NewResourceBuilders(CurrentDomain .GetAssemblies() .SelectMany(assembly => assembly.GetTypes()) .Where(type => typeof(IResourceBuilder).IsAssignableFrom(type) && type.IsClass && !type.IsAbstract) .Select(type => CreateInstance(type) as IResourceBuilder) .SelectMany(item => item?.Builders) .ToDictionary(item => item.Key, item => item.Value)); return(@this .AddMvcOptions(options => options .OutputFormatters .Add(new HalJsonOutputFormatter(serializerSettings)))); }
public static IMvcCoreBuilder AddProtobufFormatters(this IMvcCoreBuilder builder, Action <ProtobufFormatterOptions> protobufFormatterOptionsConfiguration) { if (builder == null) { throw new ArgumentNullException(nameof(builder)); } var protobufFormatterOptions = new ProtobufFormatterOptions(); protobufFormatterOptionsConfiguration?.Invoke(protobufFormatterOptions); foreach (var extension in protobufFormatterOptions.SupportedExtensions) { foreach (var contentType in protobufFormatterOptions.SupportedContentTypes) { builder.AddFormatterMappings(m => m.SetMediaTypeMappingForFormat(extension, new MediaTypeHeaderValue(contentType))); } } builder.AddMvcOptions(options => options.InputFormatters.Add(new ProtobufInputFormatter(protobufFormatterOptions))); builder.AddMvcOptions(options => options.OutputFormatters.Add(new ProtobufOutputFormatter(protobufFormatterOptions))); return(builder); }
public static IMvcCoreBuilder AddCustomMvcOptions( this IMvcCoreBuilder builder, IHostingEnvironment hostingEnvironment) => builder.AddMvcOptions( options => { if (hostingEnvironment.IsDevelopment()) { options.Filters.Add(new FormatFilterAttribute()); } options.Filters.Add(new ValidateModelStateAttribute()); options.OutputFormatters.RemoveType <StreamOutputFormatter>(); options.OutputFormatters.RemoveType <StringOutputFormatter>(); options.ReturnHttpNotAcceptable = true; });
/// <summary> /// Configures built-in ASP.NET Core MVC components. Most of this configuration can be adjusted for the developers' need. /// </summary> public void ConfigureMvc() { _mvcBuilder.AddMvcOptions(options => { options.EnableEndpointRouting = true; options.Filters.AddService <IAsyncJsonApiExceptionFilter>(); options.Filters.AddService <IAsyncQueryStringActionFilter>(); options.Filters.AddService <IAsyncConvertEmptyActionResultFilter>(); ConfigureMvcOptions?.Invoke(options); }); if (_options.ValidateModelState) { _mvcBuilder.AddDataAnnotations(); } }
/// <summary> /// Adds Fluent Validation services to the specified /// <see cref="T:Microsoft.Extensions.DependencyInjection.IMvcBuilder" />. /// </summary> /// <returns> /// An <see cref="T:Microsoft.Extensions.DependencyInjection.IMvcCoreBuilder" /> that can be used to further configure the /// MVC services. /// </returns> public static IMvcCoreBuilder AddFluentValidation(this IMvcCoreBuilder mvcBuilder, Action <FluentValidationMvcConfiguration> configurationExpression = null) { var config = new FluentValidationMvcConfiguration(); configurationExpression?.Invoke(config); mvcBuilder.Services.AddValidatorsFromAssemblies(config.AssembliesToRegister); RegisterServices(mvcBuilder.Services, config); mvcBuilder.AddMvcOptions(options => { options.ModelMetadataDetailsProviders.Add(new FluentValidationBindingMetadataProvider()); options.ModelValidatorProviders.Insert(0, new FluentValidationModelValidatorProvider(config.ImplicitlyValidateChildProperties)); }); return(mvcBuilder); }