Determine domain behind proxy in ASP.NET MVC controller

Sometimes you need to know the domain on which your app is running. If you are behind a proxy there is not a straightforward way to determine this.

To get the “real” domain name for your app check the “X-Forwarded-Host” HTTP header and use this as your host name when, for example, sending links in emails to your app.

First step is to get the host name:

public static string GetForwardedHost(HttpRequest Request)
{
   string host = Request.Headers["X-Forwarded-Host"];
   if (host == null)
   {
      host = Request.Host.ToString();
   }
   return host;
}

Next when you assemble a link for in example an email you want so sent use the code below

var host = Utils.GetForwardedHost(Request);

var callbackUrl = Url.Page(
                    "/Account/ResetPassword",
                    pageHandler: null,
                    values: new { area = "Identity", code },
                    protocol: Request.Scheme, host : host);

this.SendEmail(Input.Email, "Reset Password", $"Please reset your password by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
Share

Leave a Reply

Your email address will not be published. Required fields are marked *