configuration - Strategy for accessing an application-wide setting on the client in a .NET Core web app -
we in process of re-writing 1 of our applications using asp.net core. architecture we're trying has web api running on different url presentation. root url api change in different environments, of course, i'm trying figure out how can set configuration , access web api root url in javascript requires retrieving data. example, have ajax call fetch data api:
$.ajax({ datatype: "json", url: "http://this.url.will.change/api/whatever", //this change! success: function(response) { //load items } });
i've set appsettings.json
files various build/deploy scenarios , have them reading , injecting nicely, can store url there.
{ "data": { "defaultconnection": { "connectionstring": "whatever" } }, "appsettings": { "apirooturl": "http://apiroot/api/" } }
i considered writing urlhelper
extension provide web api root, don't think there's way inject ioptions
object static extension method. so, question this: how can make configuration setting globally available in cshtml , javascript?
update startup.cs below
public class startup { public iconfigurationroot configuration { get; set; } public startup(ihostingenvironment env, iapplicationenvironment appenv) { iconfigurationbuilder builder = new configurationbuilder() .setbasepath(appenv.applicationbasepath) .addjsonfile("appsettings.json"); configuration = builder.build(); } public void configureservices(iservicecollection services) { services.addsingleton(_ => configuration); } }
then on controller can inject configuration this
public class configurationcontroller : controller { private readonly iconfigurationroot config; public configurationcontroller (iconfigurationroot config) { this.config = config; } public string test() { return config.get<string>("appsettings:apirooturl"); } }
Comments
Post a Comment