有什么方法可以在 C# 交互中初始化 web.config 吗?

Is there any way to initialize the web.config in C# interactive?

我有一个 ASP.NET MVC 项目,我目前正在处理这个项目。我想在 C# 交互式中尝试一些代码,我单击 "Initialize interactive with project." 我可以在 C# 交互式中看到变量,类 和其他东西。

现在有一个问题是通过 web.config 定义的静态变量抛出异常。

如果我粘贴使用 web.config 变量的代码(在交互式 window 中),则无法正常工作。无论如何要解决这个问题。

我检查了 SeM 的答案,我检查了应用程序设置它什么都没有

更新 2:

我在 github 上设置了代码,阅读了答案中给出的应用程序设置,仍然没有用,代码在这里 https://github.com/anirugu/CsharpInteractiveTesting

例如,如果您将设置添加到配置文件中

<appSettings>
    <add key="Test" value="Test"/>
</appSettings>

并尝试通过ConfigurationManager读取它,它会抛出缺少引用或

的异常

The name 'ConfigurationManager' does not exist in the current context

在 C# 交互式 window 中,您可以使用关键字 #r

引用程序集
#r "System.Configuration"

然后你可以得到你的值:

#r "System.Configuration"
var settings = ConfigurationManager.OpenExeConfiguration(@"bin\Debug\YourAppName.dll"); //You can use .exe files too
Console.WriteLine(settings.AppSettings.Settings["Test"].Value);

还有!您可以通过 右键单击​​您的项目 -> Initialize Interactive with Projcet 添加项目的所有引用,VS 将为您完成所有工作。

更新

对于your example

using System.Configuration;
var settings = ConfigurationManager.OpenExeConfiguration(@"D:\TestProjects\CsharpInteractiveTesting-master\CsharpInteractiveTesting-master\CsharpInteractiveTesting\bin\Debug\CsharpInteractiveTesting.exe");
Console.WriteLine(settings.AppSettings.Settings["foo"].Value);

C# 交互本身 运行 作为一个单独的应用程序,具有单独的应用程序配置文件。如果你在 C# 中 运行 交互:

AppDomain.CurrentDomain.SetupInformation.ConfigurationFile

您会看到如下内容:

"<path to VS>\CommonExtensions\Microsoft\ManagedLanguages\VBCSharp\InteractiveComponents\InteractiveHost.exe.Config"

这就是正在使用的配置文件。当然它不包含您的变量,因此尝试执行 ConfigurationManager.AppSettings["foo"].ToString() 的代码会失败。

在运行时设置配置文件的常用方法是:

AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", fullPathToYourConfig);

但是,这应该任何对配置文件的访问之前完成。首次访问时 - 文件正在缓存,随后对路径的更改将无效。不幸的是,在允许您访问执行命令之前,C# interactive 已经使用该文件。

有各种黑客可以通过反射来重置缓存。例如(从 here 逐字复制):

public static void ChangeConfigTo(string path)
{
    AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path);
    typeof(ConfigurationManager)
        .GetField("s_initState", BindingFlags.NonPublic |
            BindingFlags.Static)
        .SetValue(null, 0);

    typeof(ConfigurationManager)
        .GetField("s_configSystem", BindingFlags.NonPublic |
            BindingFlags.Static)
        .SetValue(null, null);

    typeof(ConfigurationManager)
        .Assembly.GetTypes()
        .Where(x => x.FullName ==
            "System.Configuration.ClientConfigPaths")
        .First()
        .GetField("s_current", BindingFlags.NonPublic |
            BindingFlags.Static)
        .SetValue(null, null);
}

考虑到所有这些,如果您将该函数放在 github 示例中的 Program class 中,并在 C# 交互式中执行此操作:

Program.ChangeConfigTo(Path.GetFullPath("app.config"));

您的代码将按预期工作。您可以将此 hack 放在单独的脚本 (.csx) 文件中,并在必要时使用“#load”加载它。