从webmethod加载图像

时间:2013-11-21 10:19:18

标签: c# asp.net-mvc asp.net-mvc-3 webforms ascx

我曾经在mvc项目中工作,并且我使用以下代码加载图像:

CSHTML

 <img src="@Url.Action("GetImage", new { imageUrl =
 @asset.ImageUrl })" />

C#

public void GetImage(string imageUrl )
        {

            try
            {
                using (WebClientExtension client1 = new WebClientExtension())
                {
                    byte[] imageBytes = client1.ExecuteRequest(imageUrl );
                    if (imageBytes.Count() == 0)
                        throw new Exception();
                    HttpContext.Response.ContentType = "image/jpeg";
                    HttpContext.Response.OutputStream.Write(imageBytes, 0, imageBytes.Length);
                }
            }
            catch (Exception)
            {
                String FilePath;
                FilePath = Server.MapPath("/Images/no_image.png");
                byte[] imageBytes = System.IO.File.ReadAllBytes(FilePath);
                HttpContext.Response.ContentType = "image/jpeg";
                HttpContext.Response.OutputStream.Write(imageBytes, 0, imageBytes.Length);
            }

        }

一切正常,现在我的问题是在ascx页面中使用它。显然,@Url.Action("GetRenditionImage", new { renditionUrl = @asset.RenditionUrl })不会在ascx中工作。如何调用Web方法来实现此目的?

1 个答案:

答案 0 :(得分:1)

不要使用@ Url.Action。使用简单:

<img src="GetImage?imageUrl=sampleUrl" />