简体   繁体   中英

ASP.NET Core Web API: inject app setting value into controller route

I have an ASP.NET Core Web API project, and I would like my controllers' routes to be:

api/vX.Y/custom_name

I would have the second value in AppSettings, for example

"ApiVersion":"vX.Y"

but I'm not sure how to "inject" this value into the controller route.

If you want to enable default api version from appsettings.json , you could try to follow:

  1. appsettings.json

     { "ApiVersion": "2.1" }
  2. ConfigureApiVersioningOptions

     public class ConfigureApiVersioningOptions: IConfigureOptions<ApiVersioningOptions> { private readonly IServiceProvider _serviceProvider; public ConfigureApiVersioningOptions(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public void Configure(ApiVersioningOptions options) { var apiVersion = _serviceProvider.GetRequiredService<IConfiguration>().GetSection("ApiVersion").Value; options.DefaultApiVersion = ApiVersion.Parse(apiVersion); } }
  3. Startup.cs

     public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(options => { options.EnableEndpointRouting = false; }); services.AddApiVersioning(); services.AddSingleton<IConfigureOptions<ApiVersioningOptions>, ConfigureApiVersioningOptions>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); } }
  4. ValuesController

     [ApiController] [Route("api/v{version:apiVersion}/Values")] public class ValuesController: Controller { // GET api/values [HttpGet] public IEnumerable<string> Get() { return new string[] { "value113", "value223" }; } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM