将src属性设置为MVC3项目外部的url [英] set src property in view to a url outside of the MVC3 project

查看:53
本文介绍了将src属性设置为MVC3项目外部的url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个应用程序,该应用程序将显示存储在本地Web服务器上的图像.这是我的看法,请注意,"entry"是绝对地址,例如"C:\ Images \ Image1.jpg" .但是,当我运行它时,在控制台日志中得到不允许加载本地资源:file:///C:/Images/ImageName.jpg" .因此,也许它尝试访问客户端上的图像.如何告诉我的视图访问本地Web服务器路径,而不在客户端上查找图像源?请注意,将图像移动到项目目录中是不可选择的,因为图像存储在Web服务器上的其他驱动器上.

I am trying to create an application that will display images that are stored locally on the webserver. Here is what I have in my view, note that "entry" are absolute addresses like "C:\Images\Image1.jpg". However, when I run it, I get "Not allowed to load local resource: file:///C:/Images/ImageName.jpg" in the console log. So maybe it tries to access the image on the client. How do I tell my view to access the local webserver path and not look for the image source on the client? Please note that moving the images into project directory is not an option, because the images are stored on a different drive on the webserver.

<!-- language: c# -->
@model List<String>
<div style="height: 500px; overflow:scroll;">
<h2>
    ScreenShots for testMachine</h2>

@foreach (var entry in Model)
{          
   <div class="nailthumb-container square-thumb">
   <img alt="screenshot" src="@Url.Content(entry)" /> 

</div>
}
</div>

推荐答案

您不能将ASP.NET MVC 3应用程序之外的图像直接提供给客户端.如果客户端可以访问服务器上的任意文件,那将是一个巨大的安全漏洞.

You cannot directly serve images outside of your ASP.NET MVC 3 application to the client. That would be a huge security vulnerability if the client could access arbitrary files on your server.

您将需要编写一个控制器动作,该动作将返回它们,然后将< img> 标记的 src 属性指向该控制器动作.

You will need to write a controller action that will return them and then point your src property of your <img> tags to this controller action.

public class ImagesController: Controller
{
    public ActionResult SomeImage()
    {
        return File(@"C:\Images\foo.jpg", "image/jpeg");
    }
}

并在您的视图内:

<img src="@Url.Action("SomeImage", "Images")" alt="" />

您还可以将图像名称作为参数传递给控制器​​操作:

You could also pass the image name as parameter to the controller 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="" />

这篇关于将src属性设置为MVC3项目外部的url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆