Hrvoje
Hrvoje

Reputation: 15

How to avoid hard coding URLS

I'm hosting a .NET web api using IIS, the api features a password reset function which send the user to a reset password page, now im wondering how would could I avoid hardcoding the url

 private ReturnHandler SendResetPasswordMail(string email, string ott)
    {
        ReturnHandler result = new ReturnHandler();
        List<string> emails = new List<string>();
        emails.Add(email);
        string subject = "Promjena lozinke";
        string link = "http://axatszg-vw0038:13702/#/change-password";
        string[] parameters = { subject, "link za promjenu lozinke:", link + "?token="  + ott};

basically instead of fixating "axatszg-vw0038:13702" or "localhost:13702" could I somehow have my code access the host

Upvotes: 0

Views: 892

Answers (1)

Hossein Sabziani
Hossein Sabziani

Reputation: 3495

In Web.config you can put your value in appSettings tag, like:

<configuration>
    <appSettings>
        <add key="url" value="yourURL" />
    </appSettings>
</configuration>

Then you can get it as follows:

string link=System.Configuration.ConfigurationManager.AppSettings["url"];

in .netCore you can define the variable in the appsettings.json as follows:

appsettings.json

{
 "Logging": {
      "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
       }
  },
  "myLinks": {
      "link1": "axatszg-vw0038:13702",
      "link2": "localhost:13702"
   }
}

and read this variables in Controller with Dependency Injection:

public class TestController : ControllerBase
{
    private string myLink1 { get; set; }
    private string myLink2 { get; set; }

    public TestController(IConfiguration configuration)
    {
         this.myLink1 = configuration.GetValue<string> ("myLinks:link1");
         this.myLink2 = configuration.GetValue<string> ("myLinks:link2");
    }
}

Upvotes: 3

Related Questions