How can I safely store and access connection string details?

前端 未结 5 1524
情话喂你
情话喂你 2021-02-06 00:51

I\'m currently working on a ASP.NET MVC web site, and I\'ve come up to a point where I need to integrate a database into the website.

Normally I would simply add the app

5条回答
  •  爱一瞬间的悲伤
    2021-02-06 01:24

    Best practice is to encrypt your connection strings section. Use aspnet_regiis.exe, which can be found in various places:

    • Start – Visual Studio – Visual Studio Tools – Visual Studio Command Prompt
    • C:\Windows\Microsoft.NET\Framework\v4.0.30319 (making sure you run as an administrator)

    Before:

    
    
    
    
    
    

    Run this command:

    aspnet_regiis –pef connectionStrings c:\PathToWebSite
    

    Or, if the above command doesn't work (and you get the aspnet_regiis help text), try

    aspnet_regiis -pe connectionStrings -app "/" -site 6
    

    where the "6" is the ID of the site as reported in IIS.

    After:

    
      
       
       
        
         
         
          Rsa Key
         
         
          Bf677iFrUFW ... +4n4ZZKXCTUAu2Y=
         
        
       
       
        UDEZ ...QfXUmM5rQ==
       
      
     
    

    Now that it is garbled, you can't edit it. Decrypt like this:

    aspnet_regiis –pdf connectionStrings c:\PathToWebSite
    

    Or

    aspnet_regiis -pd connectionStrings -app "/" -site 6
    

    And then change and re-encrypt.

    To read the connection string, use the ConfigurationManager static class.

    string connStr = 
    ConfigurationManager
    .Connectionstrings["MainConnectionString"]
    .ConnectionString.ToString();
    
    var myConnection = new SqlConnection(connStr);
    
    myConnection.Open();
    

提交回复
热议问题