Convert C# Web App in C# library -- problem with Response Object
I try to convert a part of a C# Web App to make a C# Library.
I used a Response object, but this one is no more recognized in the C# library.
Here some code:
// Create a CAPTCHA image using the text stored.
CaptchaImage ci = new CaptchaImage(textCaptcha, 200, 50, "Century Schoolbook");
// Change the response headers to output a JPEG image.
this.Response.Clear();
this.Response.ContentType = "image/jpeg";
// Write the image to the response stream in JPEG format.
ci.Image.Save(this.Response.OutputStream, ImageFormat.Jpeg);
// Dispose of the CAPTCHA image object.
ci.Dispose();
How开发者_如何学运维 to use the Response object, or change it with something better? Thx
The response object represent the stream that you are sending to the client. In a desktop application there is no such concept you have no stream to send the client since your program is the client. In your above example you are writing a captchaImage to the stream this image would be displayed on the clients browser. If that is your only intent you can use an picturebox control to display the image. If you just need to save the image you can write an image to a file stream in the same manner you wrote it to the response stream.
You can place web code in a C# library, but it only makes sense for some cases. You can use HttpContext.Current.Response (so that it's static, and doesn't refer to the Response instance on a page) and call methods like "Clear" on that, but this doesn't mean anything to a non-web application that references the library. If you're creating a library to be used by web applications, this is probably fine.
You might try something like this:
HttpContext currentContext = HttpContext.Current;
// Create a CAPTCHA image using the text stored.
CaptchaImage ci = new CaptchaImage(textCaptcha, 200, 50, "Century Schoolbook");
// Change the response headers to output a JPEG image.
currentContext.Response.Clear();
currentContext.Response.ContentType = "image/jpeg";
// Write the image to the response stream in JPEG format.
ci.Image.Save(currentContext.Response.OutputStream, ImageFormat.Jpeg);
// Dispose of the CAPTCHA image object.
ci.Dispose();
You need to use some other output stream/storage for your image. E.g. you can store it in file or in database.
You should use the HttpWebRequest and HttpWebResponse objects to perform these functions within a C# winforms application (an assumption).
精彩评论