【问题标题】:Get absolute path of file on content获取内容文件的绝对路径
【发布时间】:2013-04-11 15:13:41
【问题描述】:

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

目前我正在使用

@Url.Content("~/Content/images/logo.png")

但是返回的路径不是绝对的。

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

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-3


【解决方案1】:
HttpContext.Current.Server.MapPath("~/Content/images/logo.png");

【讨论】:

  • 这个的输出是:C:\Users\...\Projects\...\Content\images\logo.png 我真正需要的是:localhost:57001/Content/images/logo.png(在开发环境) 和mydomain.com/Content/images/logo.png(在生产环境中)
  • @mosquito87 从你写问题的方式来看,你想要什么并不是很明显,所以答案就你写的内容而言是正确的(尽管与你的想法无关)。因此,我认为它不应该得到所有的反对票。
  • 老兄,你把他弄到了那里:他依靠阅读问题的人知道什么是 Web 开发。
【解决方案2】:

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

Request.Url.Authority

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

【讨论】:

  • 您还需要添加Scheme。像这样的东西: string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~/Content/images/logo.png" ))
【解决方案3】:

这对我有用:

助手:

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;
    }
}

在cshtml中的使用:

@Url.Content("~/Scripts/flot/jquery.flot.menuBar.js", true)

// example output:
// http://example.com/directory/Scripts/flot/jquery.flot.menuBar.js

【讨论】:

  • 请注意,HttpContext.Current 在 Core 中不存在。使用urlHelper.RequestContext.HttpContext
  • 我建议不要将最后一个参数设为默认/可选。已经有一个采用单个字符串参数的 UrlHelper.Content 实例方法。
  • 为了让它在 ASP.NET Core 3.1 上运行,我的助手不得不扩展接口:(this IUrlHelper urlHelper)
【解决方案4】:

这将生成一个图像(或文件)的绝对网址

Request.Url.Scheme + "://" + Request.Url.Authority + Url.Content("~/Content/images/logo.png")

这适用于 Asp.net Core

Context.Request.Scheme + "://" + Context.Request.Host + Url.Content("~/images/logo.png")

【讨论】:

  • 谢谢,过去一个小时我一直在寻找一个好的解决方案。你的效果很好。
【解决方案5】:
new Uri(Request.Url, Url.Content("~/Content/images/logo.png"))

这会调用 Uri 的 .ToString()。 您也可以将 Uri 放入变量中并调用 .AbsoluteUri。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-24
    • 2010-09-18
    • 2020-11-26
    • 2016-11-19
    • 1970-01-01
    • 2016-06-22
    相关资源
    最近更新 更多