NOTE / MVC

MVC POST 照片去前端使用方式

使用Url.Content(轉相對目錄) 方式,虛擬路徑

兩者相似都可採用

<img src="@VirtualPathUtility.ToAbsolute("~/Content/Images/logo356.png")" />來源:
<img src="@Url.Content("~/Content/Images/logo356.png")" />
使用Url.Action
public class ImagesController: Controller
{
  public ActionResult SomeImage(string imageName)
  {
    var root = @"C:\Images\";
    var path = Path.Combine(root, imageName);
    path = Path.GetFullPath(path);
    if (!path.StartsWith(root))
    {
      // Ensure that we are serving file only inside the root folder
      // and block requests outside like "../web.config"
      throw new HttpException(403, "Forbidden");
    }
    return File(path, "image/jpeg");
  }
}
<img src="@Url.Action("SomeImage", "Images", new { image = "foo.jpg" })" alt="">

兩者差異在於Url.Action能使用在其他目錄以及FTP上擷取圖片但如果使用Url.Content會有權限等等的一些問題而且只能在跟目錄底下去運作。
使用目錄外請使用Url.Action但請記得要return File相關的contentType
目錄內例:Content Images資料夾內部可以使用Url.Content

REFERENCE / 2

Loading