获得绝对URL弗朗一个ASP.NET MVC行动 [英] Getting Absolute URL fron an ASP.NET MVC Action

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

问题描述

这可能是一个伪问题,但我无法找到一个明确的指示。我有一个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 的。任何想法?

推荐答案

您可以通过以下做到这一点:

You can do it by the following:

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中去控制器 动作,还有一个更紧凑的方式:

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 */);

这里的窍门是,一旦你调用任何路由方法时指定协议 /方案,你会得到一个绝对的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.

我在这里详细的博客上讲述它:结果
<一href=\"http://gurustop.net/blog/2012/03/23/writing-absolute-urls-to-other-actions-in-asp-net-mvc/\">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开发超值服务通讯

这篇关于获得绝对URL弗朗一个ASP.NET MVC行动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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