With .NET Core, in Startup.cs you have access to IHostingEnvironment from which you can get the EnvironmentName which corresponds to the value of the ASPNETCORE_ENVIRONMENT environment variable set on the server. This is great for toggling various features on/off as well as using env-specific configs. But with a front-end that is all React.JS, is there a way to pass this value down so that the front-end is aware of it's environment as well? I can think of some potential ways it might be done but they seem a little hacky. What are the best practices for this?
问问题
2282 次
1 回答
2
当您渲染将托管您的 React 应用程序的页面时,将环境变量添加为隐藏字段,例如
@page
@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnv
<input id="hostingEnv"
type="hidden"
value=@hostingEnv.EnvironmentName />
<div id="appRoot"></div>
有关 IHostingEnvironment 的更多信息可以在这里找到。
然后,您可以使用以下代码在 React 应用程序中访问该隐藏变量的值:
const hostingEnv = document.getElementById('hostingEnv').value
至于这是否是“最佳实践”,没有最佳实践只有好的实践!然而,这种方法对我有用,尽管正如评论者所建议的那样,当然还有其他方法可以做到这一点(例如,通过单独的网络请求)。
于 2018-08-15T00:01:43.127 回答