我有这样的网址:
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);
}
在控制器内部的ActionResult中,如何从web.config访问URL并传递以下参数?
如何在web.config中传递URL,并在ASP MVC中访问URL并在控制器中传递参数?
答案 0 :(得分:4)
使用ConfigurationManager.AppSettings
从“ Web.config”文件中读取。
要定义您的URL,您可以在该文件中使用以下内容:
<appSettings>
<add
name="MyUrlFromWebConfig"
value="https://bachqy.desk.info/automalog.aspx?user={UserID}&carid={CarID}" />
</appSettings>
(请确保将&
转义/编码为&
,以确保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);
}
(还要确保对替换字符串进行URL编码,使其仍然具有有效的URL)
我会在“ Web.config”文件中的URL中使用{0}
和{1}
对 进行投票,并自己进行占位符和替换(例如{{1 }}在上面的示例中)更具表现力,而不必依靠{UserID}
调用来获取来自“ Web.config”条目的正确格式参数的数量和顺序。
答案 1 :(得分:0)
在web.config中
<appSettings>
<add key="urlPath" value="https://stackoverflow.com"/>
</appSettings>
在控制器中
var path = ConfigurationManager.AppSettings["urlPath"];