如何使用asp.net core&从appsettings.json获取配置数据反应 [英] how to get config data from appsettings.json with asp.net core & react

查看:46
本文介绍了如何使用asp.net core&从appsettings.json获取配置数据反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有react/redux的asp.net内核,并且试图将我在react/redux中的配置数据移动到appsettings.json文件中.但是一旦配置数据被移动;ClientApp如何访问配置数据?

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?

我正在使用带有Redux入门版的Reactjs和ASP.NET Core.

I'm using the Reactjs with Redux starter for ASP.NET Core.

更新

如果这不是建议的存储应用程序配置的方法,请告诉我什么.

If this is not the recommended way to store app configs please let me know what is.

推荐答案

我不建议您从客户端读取配置文件.但是,如果您愿意,我建议您创建一个读取json文件并为客户端公开一些配置的服务.

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.

您可以像这样从ASP.Net Core端进行配置

You can config from ASP.Net Core side like this

示例您在json中具有这样的配置

Example you have config like this in your json

 "EmailSettings": {
    "MailServer": "",
    "MailPort": ,
    "Email": "",
    "Password": "",
    "SenderName": "",
    "Sender": "",
    "SysAdminEmail": ""
  },

因此您需要使用config定义匹配的模型

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

然后在Startup.cs中注册

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

这篇关于如何使用asp.net core&amp;从appsettings.json获取配置数据反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆