Reputation: 19713
I'm trying to load a remote image from my Amazon S3 bucket and send it to browser in binary. I'm also trying to learn ASP.Net at the same time. I've been a classic programmer for many years and need to change. I started yesterday and have my first headache today.
On a page in my application I have this image element:
<img src="loadImage.ashx?p=rqrewrwr">
and on loadImage.ashx, I have this exact code:
-------------------------------------------------
<%@ WebHandler Language="C#" Class="Handler" %>
string url = "https://............10000.JPG";
byte[] imageData;
using (WebClient client = new WebClient()) {
imageData = client.DownloadData(url);
}
public void ProcessRequest(HttpContext context)
{
context.Response.OutputStream.Write(imageData, 0, imageData.Length);
}
-------------------------------------------------
There is probably quite a lot wrong with this, as it's my first attempt at .net and don't know what I'm doing. To start with, I'm getting the following error but sure there's more to come.
CS0116: A namespace does not directly contain members such as fields or methods
This is on line 3, which is string url = "https://............"
Upvotes: 2
Views: 8221
Reputation: 4812
For an HttpHandler, you have to put the code in the code behind... if you expand loadimage.ashx in Solution Explorer, you should see a loadimage.ashx.cs file. This file is where your logic should be, and all of it should be in the ProcessRequest method.
So loadimage.ashx should be basically empty:
<%@ WebHandler Language="C#" Class="loadimage" %>
And loadimage.ashx.cs should contain the rest:
using System.Web;
public class loadimage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string url = "https://............10000.JPG";
byte[] imageData;
using (WebClient client = new WebClient())
{
imageData = client.DownloadData(url);
}
context.Response.OutputStream.Write(imageData, 0, imageData.Length);
}
public bool IsReusable
{
get { return false; }
}
}
Alternatively, you can create an aspx page that serves the image. This removes the code behind requirement, but adds a little more overhead... create a loadimage.aspx page with the following:
<%@ Page Language="C#" AutoEventWireup="true" %>
<script language="c#" runat="server">
public void Page_Load(object sender, EventArgs e)
{
string url = "https://............10000.JPG";
byte[] imageData;
using (System.Net.WebClient client = new System.Net.WebClient())
{
imageData = client.DownloadData(url);
}
Response.ContentType = "image/png"; // Change the content type if necessary
Response.OutputStream.Write(imageData, 0, imageData.Length);
Response.Flush();
Response.End();
}
</script>
Then reference this loadimage.aspx in the image src instead of the ashx.
Upvotes: 5