【问题标题】:In an asp.net-mvc site, is there a better way to get the full base URL?在 asp.net-mvc 站点中,是否有更好的方法来获取完整的基本 URL?
【发布时间】:2013-09-08 12:36:43
【问题描述】:

我有一个 asp.net-mvc 站点,我从我的站点发送了很多电子邮件。在我以前从我的控制器发送电子邮件并使用此代码获取基本 URL 之前:

    protected string GetBaseUrl()
    {
        return string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"));
    }

那是因为我显然需要完整的 URL。因此,在我拥有 href="/GoHere" 的页面上的普通链接中,我希望将其翻译为:

  "http://www.mysite.com/GoHere"

不只是相对 URL,因为它们会出现在类似的电子邮件中

  "/GoHere"

我现在正在重构我的控制器以将所有这些代码移出它,但我发现自己在传递这个 baseURL 字符串(因为上面的函数依赖于命名空间中的 Request:

  System.Web 

而且我似乎无法在控制器类之外访问此请求对象。现在我在整个地方传递一个字符串 BaseURL 所以当我需要生成电子邮件时,我可以在基本 URL 之后附加相对 URL,但这感觉很hacky

有没有更好的方法在 asp.net-mvc 网站的控制器类之外获取 baseURL(通过 Request 对象或不通过)?

【问题讨论】:

    标签: asp.net-mvc url


    【解决方案1】:

    UrlHelper.Action 有一个接受“协议”的重载。使用它来生成符合您的路由表的完整 url。

    var baseUrl = Url.Action("Index", "Home", null, Request.Url.Scheme);
    

    MSDN Source

    在具有默认路由的默认项目 MVC 中,这将返回如下内容:

    http://mydomain.com
    

    请注意,如果您无法使用/访问 HttpRequest 对象,请考虑传入方案,或者如果您知道它始终是“https”(例如),那么您可以使用魔术(硬编码)字符串或读取它来自设置/配置文件。

    您可以通过以下方式访问控制器外部的 HttpRequest 对象:

    var request = System.Web.HttpContext.Current.Request;
    

    类似地,访问控制器的 UrlHelper 实例也会遇到同样的问题。您可以像这样创建一个实例:

    var url = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
    

    HttpRequest.RequestContext 是 .NET 4.0 的新成员。我以为我不会认为您没有指定工作版本。 MSDN source.

    【讨论】:

    • 但是如何在控制器之外访问 Request 对象呢?
    • 谢谢。 .所以我可以使用 Current.Request 获取请求对象,但我现在需要弄清楚如何复制最后一个参数( Url.Content("~")) 。 .你知道 Url.Content("~") 提供什么吗?
    • Url.Content("~") 是根路径。如果您尝试使用的 url 后面有有效的操作,则不需要使用它。只需使用 Url.Action 的 "action" 和 "controller" 参数,让路由处理其余的事情。
    【解决方案2】:

    问题在于以编程方式确定baseURL,因为它是高度相关的,并且可以通过许多 URL 访问网站。例如:

    * http://localhost/GoHere             locally
    * http://localhost:8080/GoHere        locally on another port
    * http://127.0.0.1/GoHere             locally by the loop back address
    * http://10.0.10.5/GoHere             the internal IP of the machine
    * http://72.34.56.78/GoHere           the public IP of the machine
    * http://www.mysite.com/GoHere        preferred public URL
    * http://www.bestsiteever.com/GoHere  SEO URL
    

    在配置文件、客户数据库或将baseURL 与电子邮件关联所需的任何方式中设置baseURL 会更容易。

    【讨论】:

    • 我只是想复制我在 GetBaseUr() 中的代码所做的事情
    猜你喜欢
    • 2017-07-09
    • 1970-01-01
    • 2011-01-05
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    相关资源
    最近更新 更多