ASP.NET MVC:从返回控制器CDN图像 [英] ASP.NET MVC: returning a CDN images from controller

查看:233
本文介绍了ASP.NET MVC:从返回控制器CDN图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何从MVC控制器返回的图像,但不知道如果从MVC控制器返回的CDN的图像将破坏使用CDN对于图像的目的。将使用下列code在托管web应用从CDN下载Web服务器结果,然后使之提供给用户用于从Web服务器下载?在图像下载两次,一次从CDN到Web服务器的Web服务器,然后用户?如果是这样,这比直接在Web服务器上托管的图像差?或者是图像只需下载一次,直接从CDN到最终用户?

我可以从一个MVC控制器返回的图像,并在同一时间采取CDN的优势

怎么办?

 公众的ActionResult拇指(INT ID)
    {
        //处理
        var文件=使用Server.Mappath(路径,在CDN图像);
        //做你的东西
        返回File(文件,图像/ JPG,Path.GetFileName(文件));
    }


解决方案

在你的控制器动作,你需要执行一个HTTP请求来从远程服务器映像:

 公众的ActionResult拇指(INT ID)
{
    使用(VAR的客户=新的WebClient())
    {
        字节[] =图像client.DownloadData(http://cdn.foo.com/myimage.jpg);
        返回文件(图片,图像/ JPG);
    }
}

和则:

 < IMG SRC =@ Url.Action(拇指)ALT =/>

显然现在下载图像两次。一旦在从CDN控制器和一旦从该客户端。这完全违背了该控制器行动的目的,你可以直接从CDN引用图片:

 < IMG SRC =htt​​p://cdn.foo.com/myimage.jpgALT =/>

这显然假定客户端访问CDN。

当然,如果你的控制器动作并不仅仅是获取从CDN图像并将其传输到客户端例如像取从CDN图像并调整其大小,那么你绝对应该采取第一种方式了。

I know how to return an image from the MVC controller but was wondering if returning an image in the CDN from the MVC controller will defeat the purpose of using CDN for images. Will using the following code result in the web server hosting the web application downloading from the CDN and then making it available to the user for download from the web server? Is the image downloaded twice, once from CDN to webserver and then webserver to user? If so that's worse than hosting the images directly on the webserver? Or is the image downloaded only once, directly from CDN to the end user?

How do I get to return an image from an MVC controller and at the same time take advantages of the CDN?

    public ActionResult Thumb(int id)
    {
        //process 
        var file = Server.MapPath(" path to image in the CDN ");
        //do your stuff
        return File(file, "image/jpg", Path.GetFileName(file));
    }

解决方案

In your controller action you need to perform an HTTP request to fetch the image from the remote server:

public ActionResult Thumb(int id)
{
    using (var client = new WebClient())
    {
        byte[] image = client.DownloadData("http://cdn.foo.com/myimage.jpg");
        return File(image, "image/jpg");
    }
}

and then:

<img src="@Url.Action("Thumb")" alt="" />

Obviously now the image is downloaded twice. Once in the controller from the CDN and once from the client. This completely defeats the purpose of this controller action and you could directly reference the image from the CDN:

<img src="http://cdn.foo.com/myimage.jpg" alt="" />

This obviously assumes that the client has access to the CDN.

Of course if your controller action does more than just fetching an image from a CDN and streaming it to the client like for example fetching the image from a CDN and resizing it, then you should definitely take the first approach.

这篇关于ASP.NET MVC:从返回控制器CDN图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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