如何在ASP.NET MVC中将url路径转换为完整或绝对URL?

时间:2016-05-19 17:14:26

标签: asp.net asp.net-mvc

我正在使用C#中的ASP.NET MVC开发Web应用程序。但我在检索完整或绝对网址时遇到问题。在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"。我怎么能得到它?

2 个答案:

答案 0 :(得分:9)

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

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

通常情况下,Url.Action()会返回类似于您目前期望的内容,仅提供Controller和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(即~/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

答案 1 :(得分:0)

以下内容将呈现完整的URL,包括httphttps

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

相关问题