3

I'm trying to access some web config settings from some reactjs.net components. I need these on loading of the application, but the docs on reactjs.net leave a lot to be desired. Does anyone know how this might be accomplished? Yes, I could have it call back to the server through xmlhttprequest, but I'd rather be able to pass them in through the app. Is there a way to get them in the view and pass them as params?

Thanks in advance!

2 Answers 2

1

I was able to pull this off by jumping through these hoops; for this example, I'm going to get the web.config "environment" app key value:

  1. In your react View's .cshtml file, put this in the <head>:

<script>
      var REACT_APP_RUNTIME_ENVIRONMENT = window.REACT_APP_RUNTIME_ENVIRONMENT = '@System.Web.Configuration.WebConfigurationManager.AppSettings["environment"]';
      if (REACT_APP_RUNTIME_ENVIRONMENT.indexOf('Configuration') != -1){
        REACT_APP_RUNTIME_ENVIRONMENT = window.REACT_APP_RUNTIME_ENVIRONMENT = 'dev';    // Backup value in case the above fails
      }
</script>

In the example above, I added a conditional as a fallback so you can use a flat index.html page instead of a ASP.NET MVC project and modify the runtime environment variable there instead.

  1. In your react project, you can now access window.REACT_APP_RUNTIME_ENVIRONMENT and it will pull the value "environment" from the web.config:

<appSettings> <add key="environment" value="test" /> </appSettings>

It's important to note that I've only tested this in a ASP.NET MVC project.

Sign up to request clarification or add additional context in comments.

Comments

0

It looks like you answered your own question.

Nothing stops you from firing a request on application load, retrieve the settings, store them on the client side and have your components simply use them.

There's nothing wrong with this and it keeps everything simple and clear.

3 Comments

Not really though. What if I need to set something like an API key or an address for the server? If that key is in the web.config, I can't call the server to get it because I need the API key or address to actually call the server.
if you need the URL for example, then you store that on the client side obviously. Everything else on the server side. This very much depends on what you need. You need to provide more details in your question, to make it clear what exactly you need.
I did provide very clear details of what I want in the previous comment. The client that I'm building this app for wants to be able to pass certain variables from the web.config file. They do not want to update them in two places. There should be one config to rule them all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.