【问题标题】:Get the URL of a web site获取网站的 URL
【发布时间】:2015-01-17 12:25:59
【问题描述】:

我正在开发一个 asp.net 网络表单应用程序,并在其中创建一个链接并通过电子邮件将其发送给用户以重置其密码。

唯一的问题是,当为网络外的用户创建链接时,链接会显示服务器的名称和端口号,而不是他们用来访问它的网站名称。

例如,如果我访问 https://testsite.com 然后生成电子邮件,则链接显示为 https://testserver:1111

我希望电子邮件中的链接为:https://testsite.com/reset?key=value

这是我创建链接的代码

HttpContext.Current.Request.Url.Scheme + "://" 
         + HttpContext.Current.Request.Url.Authority 
         + HttpContext.Current.Request.ApplicationPath.TrimEnd('/') 
         + "/PasswordReset.aspx;

如何获取代码以显示网站名称而不是服务器名称?

这可能是网络服务器的问题(我使用的是 IIS)吗?

【问题讨论】:

  • 您的域是在 DNS 中定义的,您的应用无法轻松访问该域。如果您通过回发或其他方式通过直接用户操作发送电子邮件,您可能能够从请求中的引荐来源获得网址。

标签: c# asp.net url


【解决方案1】:

我找到了解决方案。使用 SO 上另一个解决方案的答案,我使用了以下代码:

int lastSlash = HttpContext.Current.Request.ServerVariables["HTTP_REFERER"].LastIndexOf('/');
string uri = (lastSlash > -1) ?
           HttpContext.Current.Request.ServerVariables["HTTP_REFERER"].Substring(0, lastSlash) :
           HttpContext.Current.Request.ServerVariables["HTTP_REFERER"];

// Return the link with leading slashes
return uri + HttpContext.Current.Request.ApplicationPath.TrimEnd('/')
           + "/PasswordReset.aspx?key=value"

我需要使用服务器变量HTTP_REFERER 来获取正确的网址。

感谢大家的帮助。

【讨论】:

    【解决方案2】:

    你必须使用

    HttpContext.Current.Request.Url.Host 而不是HttpContext.Current.Request.Url.Authority

    HttpContext.Current.Request.Url.Authority 返回服务器的 DNS 名称和端口号。这就是您在电子邮件中获得 DNS(测试服务器)和端口号 (1111) https://testserver:1111 链接的原因。

    【讨论】:

    • 不幸的是,这不起作用。我仍在获取服务器名称和端口号。这可能是因为在 Web 服务器上设置了外部站点名称吗?
    【解决方案3】:

    您可以使用 appSettings 或仅使用 HttpContext.Current.Request["HTTP_HOST"]

    <appSettings>
      <add key="DOMAIN" value="www.mysite.com"/>
    </appSettings>
    

    而公正

    string domain = HttpContext.Current.Request["HTTP_HOST"];
    string myUrl = "";    
    
     if(HttpContext.Current.Request.IsSecureConnection) 
       myUrl = string.Format("https://{0}/passwordreset.aspx?key={1}",domain,yourvalue);  
     else 
       myUrl = string.Format("http://{0}/passwordreset.aspx?key={1}",domain,yourvalue);  
    
    // do something with your myUrl.
    

    【讨论】:

    • Request["HTTP_HOST"] 方法不起作用。它仍然返回服务器名称和端口号。 &lt;appSettings&gt; 解决方案的唯一问题是,如果任何用户与服务器在同一网络上,它不会向他们显示页面。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-12
    • 1970-01-01
    • 2018-06-26
    • 2016-11-28
    • 1970-01-01
    • 2014-07-21
    相关资源
    最近更新 更多