获取内容文件的绝对路径

mos*_*o87 22 asp.net-mvc asp.net-mvc-3

在asp.net mvc视图中是否有任何简单(内置)方式来获取内容文件夹中文件的绝对路径?

目前我正在使用

@Url.Content("~/Content/images/logo.png")
Run Code Online (Sandbox Code Playgroud)

但返回的路径并不是绝对的.

我知道有可能为这种情况建立自己的助手,但我想知道是否有更简单的方法......

Jef*_*ian 33

这对我有用:

帮手:

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)

// example output:
// http://example.com/directory/Scripts/flot/jquery.flot.menuBar.js
Run Code Online (Sandbox Code Playgroud)


Sho*_*hoe 14

这将生成图像(或文件)的绝对URL

Request.Url.Scheme + "://" + Request.Url.Authority + Url.Content("~/Content/images/logo.png")
Run Code Online (Sandbox Code Playgroud)

这适用于Asp.net Core

Context.Request.Scheme + "://" + Context.Request.Host + Url.Content("~/images/logo.png")
Run Code Online (Sandbox Code Playgroud)


Zip*_*pyV 5

Url.Content确实返回绝对路径.你想要的是域(和端口).您可以使用以下方式获取当前域:

Request.Url.Authority
Run Code Online (Sandbox Code Playgroud)

然后将此字符串与图像的绝对路径字符串组合在一起.它将返回域名,如果您在不同的端口上,还将包含端口号.

  • 您还需要添加Scheme.像这样的Somethig:string.Format("{0}:// {1} {2}",Request.Url.Scheme,Request.Url.Authority,Url.Content("〜/ Content/images/logo.png" )) (2认同)

小智 0

HttpContext.Current.Server.MapPath("~/Content/images/logo.png");
Run Code Online (Sandbox Code Playgroud)

  • @mosquito87从你的问题的编写方式来看,你想要什么并不明显,所以答案相对于你所写的内容是正确的(尽管与你的想法无关)。因此,我认为它不应该得到所有的反对票。 (3认同)