从ASP.NET MVC操作获取绝对URL [英] Getting Absolute URL from an ASP.NET MVC Action

查看:56
本文介绍了从ASP.NET MVC操作获取绝对URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This probably is a dummy question but I cannot find a clear indication. I have a POCO class in a MVC3 web application whose only purpose is managing the backup of some files in the server. Typically it creates a backup and returns the filename to the controller, which sends an email with the URL for downloading it. This works fine, but I cannot build the absolute URL to be sent. No matter which function I use, I always get a relative URL, like /Backup/TheFile.zip, rather than e.g. http://www.somesite.com/Backup/TheFile.zip. I tried:

VirtualPathUtility.ToAbsolute("~/Backup/SomeFile.zip");
HttpRuntime.AppDomainAppVirtualPath + "/Backup/SomeFile.zip";
Url.Content("~/Backup/SomeFile.zip");

,但是它们都返回类似/Backup/SomeFile.zip 的内容.有什么主意吗?

but they all return something like /Backup/SomeFile.zip. Any idea?

推荐答案

您可以执行以下操作:

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()

除了本示例中的 Url.Action()外,您还可以使用 Url.Content()或任何路由方法,或者实际上只是传递路径.

Instead of Url.Action() in this sample, you can also use Url.Content(), or any routing method, or really just pass a path.

但是,如果URL确实进入了 Controller Action ,则有一种更紧凑的方法:

But if the URL does go to a Controller Action, there is a more compact way:

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

这里的窍门是,一旦在调用任何路由方法时指定了 protocol /scheme,您将获得一个绝对URL.在可能的情况下,我建议您这样做,但在第一个示例中,如果需要,您也可以采用更通用的方式.

The trick here is that once you specify the protocol/scheme when calling any routing method, you get an absolute URL. I recommend this one when possible, but you also have the more generic way in the first example in case you need it.

我已在此处详细介绍了此博客:
http://gurustop.net/blog/2012/03/23/writing-absolute-urls-to-other-actions-in-asp-net-mvc/

I have blogged about it in details here:
http://gurustop.net/blog/2012/03/23/writing-absolute-urls-to-other-actions-in-asp-net-mvc/

Meligy的AngularJS&Web Dev Goodies通讯

这篇关于从ASP.NET MVC操作获取绝对URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆