asp.net-mvc 获取内容上文件的绝对路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16084081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get absolute path of file on content
提问by mosquito87
Is there any easy (built in) way in an asp.net mvc view to get the absolute path of a file in the content folder?
在 asp.net mvc 视图中是否有任何简单(内置)的方法来获取内容文件夹中文件的绝对路径?
At the moment I'm using
目前我正在使用
@Url.Content("~/Content/images/logo.png")
But the path returned isn't absolute.
但是返回的路径不是绝对的。
I know it is possible to build its own helper for such cases but I'd like to know if there's any easier way...
我知道可以为这种情况构建自己的助手,但我想知道是否有更简单的方法......
回答by Jeff Tian
This works for me:
这对我有用:
A helper:
一个帮手:
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;
}
}
Usage in cshtml:
在 cshtml 中的用法:
@Url.Content("~/Scripts/flot/jquery.flot.menuBar.js", true)
// example output:
// http://example.com/directory/Scripts/flot/jquery.flot.menuBar.js
回答by Shoe
This will generate an absolute url to an image (or file)
这将生成图像(或文件)的绝对 url
Request.Url.Scheme + "://" + Request.Url.Authority + Url.Content("~/Content/images/logo.png")
This works in Asp.net Core
这适用于 Asp.net Core
Context.Request.Scheme + "://" + Context.Request.Host + Url.Content("~/images/logo.png")
回答by ZippyV
Url.Content does return the absolute path. What you want is the domain (and port). You can get the current domain by using:
Url.Content 确实返回绝对路径。你想要的是域(和端口)。您可以使用以下方法获取当前域:
Request.Url.Authority
Then combine this string with the absolute path string of your image. It will return the domain name and if you are on a different port will also include the port number.
然后将此字符串与图像的绝对路径字符串组合。它将返回域名,如果您在不同的端口上,还将包括端口号。
回答by juFo
new Uri(Request.Url, Url.Content("~/Content/images/logo.png"))
this calls the .ToString() of Uri. You can also put Uri in a variable and call .AbsoluteUri.
这调用了 Uri 的 .ToString()。您还可以将 Uri 放在变量中并调用 .AbsoluteUri。
回答by juFo
HttpContext.Current.Server.MapPath("~/Content/images/logo.png");

