1

I have settings in AppSettings (web.config) and I need to pass them to an external javascript file.

In ASP.NET I would think of an ASHX handler to write the javascript file to the response replacing placeholders with the settings values.

Is there a better way to do it in ASP.NET MVC? Thank you.

1 Answer 1

3

You could send them via a JsonResult?

In your JS, you'd have a request which sends a GET/POST request to a particular action (let's call it GetAppSetting(), and the corresponding value is returned in the response.

For security reasons, I would restrict what can be requested though...

public JsonResult GetAppSetting(string id)
{
  //You could check what's been requested here if you want to make sure you're only returning information that you may not wish to send.
  string appSetting = AppSettings[id];

  if(string.IsNullOrEmpty(appSetting) == false)
  {
    return Json(appSetting, JsonRequestBehavior.AllowGet);
  }

  //Handle non-existent settings here...
  throw new Exception("This setting does not exist");
}

Alternatively, it has been suggested by Chris Marisic in the comments that you may want to absolutely limit this to just a specific set of key/values for developer reasons. Therefore, here is a quick example of that...

public JsonResult GetAppSettings()
{
  var appSettings = new Dictionary<string, string>();
  appSettings.Add("myAppSetting1", AppSettings["myAppSetting1"]);
  appSettings.Add("myAppSetting2", AppSettings["myAppSetting2"]);
  appSettings.Add("myAppSetting3", AppSettings["myAppSetting3"]);

  return Json(appSettings, JsonRequestBehavior.AllowGet);
}

Note the JsonRequestBehavior.AllowGet in the JsonResults (MVC 2 only). This is because, by default, ASP.NET MVC 2 will not allow GET requests on actions which return a JsonResult. You can circumvent this by adding the JsonRequestBehaviour, but I should probably mention that you should consider doing a post request in order to retrieve this information, and remove this behaviour in your action.

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

2 Comments

I would not recommend using your approach to query the app config, that leaves alot of room for developer error. I would recommend to just have GetSettings() and have it return a json object that contains all of the public settings information so it's much less likely to ever inadvertently leak information.
@Chris - Please could you elaborate with 'developer error'? It's also not less likely that you'll inadvertently leak information if you simply send all of it!!

Your Answer

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