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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With