【问题标题】:How to convert url path to full or absolute url in ASP.NET MVC?如何在 ASP.NET MVC 中将 url 路径转换为完整或绝对 url?
【发布时间】:2016-05-19 17:14:26
【问题描述】:

我正在使用 C# 中的 ASP.NET MVC 开发 Web 应用程序。但我在检索完整或绝对 url 时遇到问题。在 ASP.NET MVC 中,我们得到这样的 url。 Url.Content("~/path/to/page")。它将返回"path/to/page"。但我想做的是我有一个这样的字符串 - "~/controller/action"

假设我的网站域是 www.example.com。如果我使用Url.Content("~/controller/action"),它只会返回“控制器/动作”。我想得到"www.example.com/controller/action"。我怎样才能得到它?

【问题讨论】:

  • 你试过this:Url.Action("action", "controller", null, Request.Url.Scheme)吗?

标签: asp.net asp.net-mvc


【解决方案1】:

如果您可以使用控制器/动作名称...

您应该为此使用Url.Action() 方法。

通常情况下,Url.Action() 将返回类似于您目前所期望的仅提供控制器和操作名称的内容:

// This would yield "Controller/Action"
Url.Action("Action","Controller"); 

但是,当您传入协议参数(即httphttps 等)时,该方法实际上将返回一个完整的绝对 URL。为方便起见,您可以使用Request.Url.Scheme 属性访问相应的协议,如下所示:

// This would yield "http://your-site.com/Controller/Action"
Url.Action("Action", "Controller", null, Request.Url.Scheme);

你可以see an example of this in action here

如果您只有一个相对 URL 字符串...

如果您只能访问相对 URL(即 ~/controller/action),那么您可能需要创建一个函数来扩展 Url.Content() 方法的当前功能以支持提供绝对 URL:

public static class UrlExtensions
{
    public static string AbsoluteContent(this UrlHelper urlHelper, string contentPath)
    {
        // Build a URI for the requested path
        var url = new Uri(HttpContext.Current.Request.Url, urlHelper.Content(contentPath));
        // Return the absolute UrI
        return url.AbsoluteUri;
    }
}

如果定义正确,这将允许您简单地将您的 Url.Content() 调用替换为 Url.AbsoluteContent(),如下所示:

Url.AbsoluteContent("~/Controller/Action")

你可以see an example of this approach here

【讨论】:

  • 对不起。这无法解决我的问题。这是一个很好的答案,但是。我想要的是我想将“~/Controller/Action”之类的字符串转换为完整的url。
  • 我已经更新了答案,因为我意识到您想要实际使用相对 URL。如果您遇到任何问题,请告诉我。
【解决方案2】:

下面会渲染一个完整的url,包括http或者https

var url = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
var fullUrl = url.Action("YourAction", "YourController", new { id = something }, protocol: System.Web.HttpContext.Current.Request.Url.Scheme);

输出

https://www.yourdomain.com/YourController/YourAction?id=something

【讨论】:

    猜你喜欢
    • 2013-06-29
    • 2015-01-24
    • 1970-01-01
    • 2021-10-18
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 2011-05-25
    相关资源
    最近更新 更多