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

查看:18
本文介绍了如何使用 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?

我将 Reactjs 与 Redux starter 一起用于 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天全站免登陆