从ASP.NET MVC Action获取绝对URL

Naf*_*tis 70 c# asp.net-mvc asp.net-mvc-3

这可能是一个虚拟问题,但我找不到明确的指示.我在MVC3 Web应用程序中有一个POCO类,其唯一目的是管理服务器中某些文件的备份.通常,它会创建一个备份并将文件名返回给控制器,控制器会发送一封电子邮件,其中包含用于下载它的URL.这工作正常,但我无法构建要发送的绝对URL.无论我使用哪种功能,我总是得到一个相对的URL,比如/Backup/TheFile.zip,而不是http://www.somesite.com/Backup/TheFile.zip.我试过了:

VirtualPathUtility.ToAbsolute("~/Backup/SomeFile.zip");
HttpRuntime.AppDomainAppVirtualPath + "/Backup/SomeFile.zip";
Url.Content("~/Backup/SomeFile.zip");
Run Code Online (Sandbox Code Playgroud)

但它们都返回类似/Backup/SomeFile.zip的东西.任何的想法?

Mel*_*igy 109

您可以通过以下方式完成此操作:

var urlBuilder =
    new System.UriBuilder(Request.Url.AbsoluteUri)
        {
            Path = Url.Action("Action", "Controller"),
            Query = null,
        };

Uri uri = urlBuilder.Uri;
string url = urlBuilder.ToString();
// or urlBuilder.Uri.ToString()
Run Code Online (Sandbox Code Playgroud)

Url.Action()您也可以使用Url.Content()或使用任何路由方法,或者只是传递路径,而不是在此示例中.

但是,如果URL确实转到了a Controller Action,则有一种更紧凑的方式:

var contactUsUriString =
    Url.Action("Contact-Us", "About",
               routeValues: null /* specify if needed */,
               protocol: Request.Url.Scheme /* This is the trick */);
Run Code Online (Sandbox Code Playgroud)

这里的技巧是,一旦protocol在调用任何路由方法时指定/ scheme,就会得到一个绝对URL.我尽可能推荐这个,但是如果需要,你也可以在第一个例子中使用更通用的方法.

我在这里详细介绍了它的内容:http:
//gurustop.net/blog/2012/03/23/writing-absolute-urls-to-other-actions-in-asp-net-mvc/

摘自Meligy的AngularJS和Web Dev Goodies时事通讯

  • 协议的绝佳技巧.非常感谢你!! (4认同)

Chr*_*ris 35

从控制器内部:

var path = VirtualPathUtility.ToAbsolute(pathFromPoco);
var url = new Uri(Request.Url, path).AbsoluteUri
Run Code Online (Sandbox Code Playgroud)

  • 结合Uri课程,这就是你所需要的.有点无意义的评论. (6认同)

Jef*_*ian 18

这对我有用:

using System;
using System.Web;
using System.Web.Mvc;

public static class UrlExtensions
{
    public static string Content(this UrlHelper urlHelper, string contentPath, bool toAbsolute = false)
    {
        var path = urlHelper.Content(contentPath);
        var url = new Uri(HttpContext.Current.Request.Url, path);

        return toAbsolute ? url.AbsoluteUri : path;
    }
}
Run Code Online (Sandbox Code Playgroud)

在cshtml中的用法:

@Url.Content("~/Scripts/flot/jquery.flot.menuBar.js", true)
Run Code Online (Sandbox Code Playgroud)