在 asp.net mvc 视图中是否有任何简单的(内置)方法来获取内容文件夹中文件的绝对路径?
目前我正在使用
@Url.Content("~/Content/images/logo.png")
但是返回的路径不是绝对的。
我知道可以为这种情况建立自己的助手,但我想知道是否有更简单的方法......
在 asp.net mvc 视图中是否有任何简单的(内置)方法来获取内容文件夹中文件的绝对路径?
目前我正在使用
@Url.Content("~/Content/images/logo.png")
但是返回的路径不是绝对的。
我知道可以为这种情况建立自己的助手,但我想知道是否有更简单的方法......
这对我有用:
帮手:
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
这将生成图像(或文件)的绝对 URL
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")
Url.Content 确实返回绝对路径。您想要的是域(和端口)。您可以使用以下方法获取当前域:
Request.Url.Authority
然后将此字符串与图像的绝对路径字符串结合起来。它将返回域名,如果您在不同的端口上,还将包括端口号。
new Uri(Request.Url, Url.Content("~/Content/images/logo.png"))
这调用了 Uri 的 .ToString()。您也可以将 Uri 放入变量中并调用 .AbsoluteUri。
HttpContext.Current.Server.MapPath("~/Content/images/logo.png");