I have an URL like this:
https://bachqy.desk.info/automalog.aspx?user=""&carid=""
In my controller, I have an action method that passes two parameters in the above, to redirect the URL. I do not want to hardcode the URL in the controller.
public ActionResult NavigateToCar(string userId, string CarID)
{
return new RedirectResult(
"https://bachqy.desk.info/automalog.aspx?user="+userId+"&carid="+CarID);
}
Inside the controller, in the ActionResult, how can I access the URL from the web.config and pass the following parameters?
How can I pass the URL in the web.config and access the URL and pass the parameters in the controller in ASP MVC?
Use ConfigurationManager.AppSettings to read from your "Web.config" file.
To define your URL, you could use something like this in that file:
<appSettings>
<add
name="MyUrlFromWebConfig"
value="https://bachqy.desk.info/automalog.aspx?user={UserID}&carid={CarID}" />
</appSettings>
(Be sure to escape/encode the & as & to keep your XML valid)
Later in your code, use:
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);
}
(Also be sure to URL-encode the replacement strings to still have a valid URL)
I would vote against using {0} and {1} in the URL in the "Web.config" file, and do your own placeholders and replacement (like {UserID} in my example above) to be more expressive and not rely on your String.Format call to have the correct number and order of format arguments coming from the "Web.config" entry.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With