asp.net - 我如何加密然后解密 Web.config 内容

标签 asp.net

我在我的 Web.config 文件中为 ASP.NET MVC Web 应用程序添加了以下设置

<appSettings>
    //code goes here
    <add key="ApiUserName" value="testuser" />
    <add key="ApiPassword" value=,,,… />
    <add key="ApiURL" value="http://win-spdev:8400/servlets/AssetServlet" />
  </appSettings>

这些设置用于在我的 Controller 操作方法中启动 API 调用,如下所示:-

    using (var client = new WebClient())
                    {
                        var query = HttpUtility.ParseQueryString(string.Empty);
                        foreach (string key in formValues)
                        {
                            query[key] = this.Request.Form[key];
                        }

query["username"] = System.Web.Configuration.WebConfigurationManager.AppSettings["ApiUserName"];
query["password"] = System.Web.Configuration.WebConfigurationManager.AppSettings["ApiPassword"];
query["assetType"] = "Rack";
query["operation"] = "AddAsset";
string apiurl = System.Web.Configuration.WebConfigurationManager.AppSettings["ApiURL"];
var url = new UriBuilder(apiurl);

我已阅读以下有关加密和解密 web.config 文件的链接 http://msdn.microsoft.com/en-us/library/zhhddkxy.aspx 。但我不确定如何在上面的操作方法中进行链接中描述的加密和解密?

最佳答案

基本上有两种标准方法可以做到这一点,您可以将 aspnet_regiis 与 DPAPI 或 RSA 一起使用。使用 RSA 的优点是,如果您的应用程序在多台计算机上运行,​​您可以使用 RSA key 加密一次,并在所有计算机上使用相同的 key 进行解密,而使用 DPAPI 时,您必须专门针对其所在的每台计算机进行加密继续运行。

例如,使用 DPAPI,您基本上只需转到框架目录并运行以下命令。

aspnet_regiis -pe“connectionStrings”-app“/MyApplication”

上面的命令将对“MyApplication”的连接字符串进行加密,该字符串将是您在 IIS 中的应用程序的名称。现在,它必须在运行应用程序的计算机上运行,​​因此您首先需要将应用程序复制到服务器。使用 RSA 方法,您可以在您的计算机(或构建服务器)上加密,然后部署到您想要的任何计算机。

您可以在http://msdn.microsoft.com/library/dtkwfdky.aspx查看详细演练。

这样做的好处是,您不必担心如何访问应用程序设置和连接字符串,您只需像平常一样使用 ConfigurationManager.Appsettings 和 ConfigurationManager.ConnectionStrings 即可,框架将负责执行此操作为您解密。

关于asp.net - 我如何加密然后解密 Web.config 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18048038/

相关文章:

c# - ASP 到 ASP.NET 帮助函数

c# - 在查询字符串中使用点 ("."时未设置 CORS header )

asp.net - 如何让旧的 VBScript ASP sendemail 在 Azure 上运行?

asp.net - Nginx 无法将 Docker 部署到 Amazon

javascript - 从文本框中过滤 gridview 时显示一些消息

javascript - onClientClick return Function() 仍然触发 OnClick

c# - 如何在 visual studio designer 中使类型为 collection<string> 的用户控件属性可编辑/可设置

asp.net - 将 FormsAuthentication 替换为 SessionAuthenticationModule (SAM) 以实现 Claims Aware 身份

asp.net - 如何暂时关闭正在运行的网站并给出消息 "This site is Temprorary unavailable"

asp.net - 在 ASP.NET Core 中注册 ControllerModel 的操作