问题
I'm using asp.net core with react/redux and i'm trying to move my config data that is in react/redux into the appsettings.json file. But once the config data has been moved; how is the config data accessible to the ClientApp?
I'm using the Reactjs with Redux starter for ASP.NET Core.
update
If this is not the recommended way to store app configs please let me know what is.
回答1:
I would not recommend reading the config file from your client side. But if you want to do I would suggest you create a service that read the json file and expo some configuration for client side.
You can config from ASP.Net Core side like this
Example you have config like this in your json
"EmailSettings": {
"MailServer": "",
"MailPort": ,
"Email": "",
"Password": "",
"SenderName": "",
"Sender": "",
"SysAdminEmail": ""
},
So you need to define the matching model with config
public class EmailSettings
{
public string MailServer { get; set; }
public int MailPort { get; set; }
public string SenderName { get; set; }
public string Sender { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string SysAdminEmail { get; set; }
}
Then register in Startup.cs
services.Configure<EmailSettings>(configuration.GetSection("EmailSettings"));
So you can use in your service
private readonly IOptions<EmailSettings> _emailSetting;
public EmailSender(IOptions<EmailSettings> emailSetting)
{
_emailSetting = emailSetting;
}
public string GetConfig(){
return _emailSetting.Value.SenderName;
}
回答2:
I suggest you to manage independently client and server configurations.
For server configurations management the appsettings.json
is the right place.
In the client you can handle the configurations as environment variables in the following way:
1) create a configuration file for each environment, for example:
.env.dev
.env.test
.env.prod
Suppose you have "SOME_URL" variable in each file:
.env.dev:
SOME_URL=http://localhost:4000/
.env.test
SOME_URL=http://mytesturl/
and so on and so forth
2) Use webpack environment plugin:
plugins: options.plugins.concat([
new webpack.EnvironmentPlugin({
SOME_URL: JSON.stringify(process.env.SOME_URL),
...
}),
]),
3) this is the script I use for launching the app:
"start": "cross-env env-cmd -f .env.dev node server",
4) Access the configuration in the client:
process.env.SOME_URL;
With webpack you are using bundled code that runs in the browser. The process.env
context doesn’t exist in the browser. The way it works is that you’ve told the webpack Environment plugin that the value of process.env.SOME_URL
should be available in the bundled client code. When bundling, the plugin simply looks for the exact text process.env.SOME_URL
in the code and replaces it with the actual value.
来源:https://stackoverflow.com/questions/56446428/how-to-get-config-data-from-appsettings-json-with-asp-net-core-react