如何将我的MVC web.config值传递给我的角度模块配置方法?
我想用我的MVC web.config中的参数设置$ logProvider.debugEnabled值。这样我就不用记得在从Dev转到Test到Prod时更改设置。
我有found a solution用于传递可从我的角度控制器访问的参数,但我在配置方法中需要它们。
以下是我现在在app.js中的内容
(function () {
var app = angular.module("myApp", ['configSettings']);
app.config('settings', [function (settings, $logProvider) {
var envr = settings.serverConfig;
if (!envr == "LOCAL") {
$logProvider.debugEnabled(false);
}
}]);
}());
提前致谢,
约翰
答案 0 :(得分:4)
我正在使用自定义http处理程序:
public class JavascriptResourceHandler : IHttpHandler
{
#region IHttpHandler Members
public bool IsReusable
{
// Return false in case your Managed Handler cannot be reused for another request.
// Usually this would be false in case you have some state information preserved per request.
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
var sb = new StringBuilder();
sb.Append("var js = {};");
sb.Append("js.settings = { ");
var settings = ConfigurationManager.AppSettings.AllKeys.Where(k => k.StartsWith("JS_")).ToList();
for (int i = 0; i < settings.Count; i++)
{
var key = settings[i];
var name = key.Replace("JS_", string.Empty);
var value = ConfigurationManager.AppSettings[key];
sb.Append(name);
sb.Append(":");
sb.Append("'");
sb.Append(HttpUtility.JavaScriptStringEncode(value));
sb.Append("'");
if (i != settings.Count - 1)
sb.Append(",");
}
sb.Append("};");
context.Response.Clear();
context.Response.ContentType = "text/javascript";
context.Response.Write(sb.ToString());
}
#endregion
}
然后将此处理程序添加到<system.webServer><handlers>
:
<add name="JavascriptResourceHandler" verb="GET" path="JavascriptResourceHandler.axd" type="MyNamespace.JavascriptResourceHandler, MyAssembly, Version=1.0.*, Culture=neutral" />
从html中引用它:
<script src="~/JavascriptResourceHandler.axd"></script>
然后使用JS_前缀来将配置值传播到javascript(这是出于安全原因,因为我们通常不希望将所有应用程序设置传播到客户端代码):
<add key="JS_Key" value="MyConfigValue" />
配置值将在javascript中提供:
var myValue = js.settings.Key; // the JS_ prefix will be automatically removed
你的例子:
(function () {
var app = angular.module("myApp", ['configSettings']);
app.config('settings', [function (settings, $logProvider) {
var envr = js.settings.serverAppSettingsKeyWithoutJSPrefix;
if (!envr == "LOCAL") {
$logProvider.debugEnabled(false);
}
}]);
}());