2016-09-22 42 views
0

我用下面的方法来加密在我的web.config连接字符串运行:加密的连接字符串失败时从服务器

public static void EncryptConnectionString() 
{ 
    var section = GetConfigSection(); 

    if (section.SectionInformation.IsProtected) return; 

    section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider"); 
    section.SectionInformation.ForceSave = true; 
    section.CurrentConfiguration.Save(); 

} 

private static ConnectionStringsSection GetConfigSection() 
{ 
    var config = WebConfigurationManager.OpenWebConfiguration("~"); 
    var section = config.GetSection("connectionStrings"); 
    if (section.ElementInformation.IsLocked || section.SectionInformation.IsLocked) return null; 

    return section as ConnectionStringsSection; 
} 
  • 我放在调用此方法Global.asax的Application_Start()方法
  • 在本地运行时,该方法起作用,我可以看到连接字符串变为加密。
  • 从服务器运行时,该方法不起作用。我运行该应用程序,并且服务器连接字符串上的web.config保持未加密状态。
  • 在别处手动调用该方法似乎会导致它的工作。如果我从应用程序的HomeController调用它,我可以看到连接字符串已被加密。
  • Global.asax的其他方法Application_Start()似乎可以正常工作,因为我可以看到正在使用的已注册捆绑包。

那么为什么不调用这个方法,编辑web.config,从Application_Start()调用时工作?

回答

0

当应用程序第一次启动时,或者更确切地说,应用程序收到第一个请求时,会调用Application_Start。尝试点击主控制器并让它无所事事,然后检查web.config是否被加密。