[英]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:我有一个 ASP.NET 核心 Web API 项目,我希望我的控制器的路线是:
api/vX.Y/custom_name
I would have the second value in AppSettings, for example例如,我会在 AppSettings 中有第二个值
"ApiVersion":"vX.Y"
but I'm not sure how to "inject" this value into the controller route.但我不确定如何将此值“注入”到 controller 路由中。
If you want to enable default api version from appsettings.json
, you could try to follow:如果您想从 appsettings.json 启用默认appsettings.json
版本,您可以尝试遵循:
appsettings.json
{ "ApiVersion": "2.1" }
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); } }
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(); } }
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.