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)
Url.Content确实返回绝对路径.你想要的是域(和端口).您可以使用以下方式获取当前域:
Request.Url.Authority
Run Code Online (Sandbox Code Playgroud)
然后将此字符串与图像的绝对路径字符串组合在一起.它将返回域名,如果您在不同的端口上,还将包含端口号.
小智 0
HttpContext.Current.Server.MapPath("~/Content/images/logo.png");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30135 次 |
| 最近记录: |