在 web.config 中添加 URL 并在控制器中访问它

cra*_*dev 3 c# asp.net asp.net-mvc

我有一个这样的网址:

https://bachqy.desk.info/automalog.aspx?user=""&carid=""

在我的控制器中,我有一个 action 方法,它传递上面的两个参数,以重定向 URL。我不想在控制器中硬编码 URL。

public ActionResult NavigateToCar(string userId, string CarID)
{
    return new RedirectResult(
        "https://bachqy.desk.info/automalog.aspx?user="+userId+"&carid="+CarID);
}
Run Code Online (Sandbox Code Playgroud)

在控制器内部,在 ActionResult 中,如何从 web.config 访问 URL 并传递以下参数?

如何在 web.config 中传递 URL 并访问 URL 并在 ASP MVC 中的控制器中传递参数?

Uwe*_*eim 8

用于ConfigurationManager.AppSettings从“Web.config”文件中读取。

要定义您的 URL,您可以在该文件中使用类似的内容:

<appSettings>
    <add 
       name="MyUrlFromWebConfig" 
       value="https://bachqy.desk.info/automalog.aspx?user={UserID}&amp;carid={CarID}" />
</appSettings>
Run Code Online (Sandbox Code Playgroud)

(确保对&as进行转义/编码&amp;以保持 XML 有效)

稍后在您的代码中,使用:

public ActionResult NavigateToCar(string userId, string CarID)
{
    var url = ConfigurationManager.AppSetting["MyUrlFromWebConfig"];

    url = url.Replace("{UserID}", Server.UrlEncode(userId));
    url = url.Replace("{CarID}", Server.UrlEncode(carID));

    return new RedirectResult(url);
}
Run Code Online (Sandbox Code Playgroud)

(还要确保对替换字符串进行 URL 编码以仍然具有有效的 URL)


我会投反对使用{0},并{1}在“Web.config文件”文件的URL,并(像做自己的占位符和替换{UserID}在我上面的例子)是更具表现力,而不是靠你的String.Format电话有正确数量和顺序来自“Web.config”条目的格式参数。