Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add URL in web.config and access it in controller

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?

like image 291
crazydev Avatar asked Feb 04 '26 08:02

crazydev


1 Answers

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}&amp;carid={CarID}" />
</appSettings>

(Be sure to escape/encode the & as &amp; 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.

like image 165
Uwe Keim Avatar answered Feb 05 '26 21:02

Uwe Keim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!