简体   繁体   中英

.NET Core Web API: Possible to assign controller route in appsettings.json config file?

I'd like my Web API controller's route to be assigned dynamically via the config file (appsettings.json).

I figured maybe it would be a simple solution. However, trying this [unsurprisingly] doesn't work:

private static string route = Configuration.GetValue<string>("Path");

[Route(route)]
// action

Which results in An attribute argument must be a constant expression, typeof expression, or array creation expression of an attribute parameter type

Is it possible do do what I desire? If so, what are the best practices for doing so? I can't find much documentation on it, and would prefer not to roll my own HttpListener to accomplish a relatively simple goal.

Turns out I was overthinking things.

In Startup

public void Configure(IApplicationBuilder app)
{
    // basic stuff
    var config = services.GetService<IConfiguration>();
    string route = config.GetValue<string>("Path");

    app.UseMvc(routes => {
        routes.MapRoute("someName", route, new { controller = "myController", action = "myAction"});
    });
}

Easy as pie.

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