【问题标题】:ASP.NET Core Web API: inject app setting value into controller routeASP.NET Core Web API:将应用设置值注入控制器路由
【发布时间】:2019-11-08 11:33:23
【问题描述】:

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

api/vX.Y/custom_name

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

"ApiVersion":"vX.Y"

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

【问题讨论】:

  • 这看起来像 the XY Problem 的情况 - 您对 X 有问题(API 版本控制?URL 中的默认版本?)并认为 Y 是解决方案(将版本硬编码在网址)。当这不起作用时,您会询问 Y,而不是 X。您的实际问题是什么?
  • 您应该能够在Startup.csGlobal.asax 中为路由添加前缀
  • 为什么要在控制器路由中注入值?
  • 你要注入默认的api版本吗?

标签: c# asp.net-core asp.net-web-api .net-core


【解决方案1】:

如果您想从appsettings.json启用默认的api版本,您可以尝试关注:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-28
    • 2016-07-12
    • 2018-08-25
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    • 2016-09-07
    • 2021-02-02
    相关资源
    最近更新 更多