[英]Add URL in web.config and access it in controller
我有一个像这样的 URL:
https://bachqy.desk.info/automalog.aspx?user=""&carid=""
在我的 controller 中,我有一个传递上述两个参数的操作方法,以重定向 URL。 我不想在 controller 中硬编码 URL。
public ActionResult NavigateToCar(string userId, string CarID)
{
return new RedirectResult(
"https://bachqy.desk.info/automalog.aspx?user="+userId+"&carid="+CarID);
}
在 controller 内部,在 ActionResult 中,如何从 web.config 中访问 URL 并传递以下参数?
How can I pass the URL in the web.config and access the URL and pass the parameters in the controller in ASP MVC?
使用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}
,并使用您自己的占位符和替换(如我上面示例中的{UserID}
)更具表现力,而不是依赖于您的String.Format
调用具有来自“Web.config”条目的格式 arguments 的正确编号和顺序。
在 web.config
<appSettings>
<add key="urlPath" value="https://stackoverflow.com"/>
</appSettings>
在 controller
var path = ConfigurationManager.AppSettings["urlPath"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.