繁体   English   中英

ASP.NET 核心 Web API:将应用设置值注入 Z594C103F2C6E04C3C3DAZAB059F031 路由

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

我有一个 ASP.NET 核心 Web API 项目,我希望我的控制器的路线是:

api/vX.Y/custom_name

例如,我会在 AppSettings 中有第二个值

"ApiVersion":"vX.Y"

但我不确定如何将此值“注入”到 controller 路由中。

如果您想从 appsettings.json 启用默认appsettings.json版本,您可以尝试遵循:

  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" }; } }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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