This code at the bottom worked for me.
Inside an ASP.NET page, I decided to send the exception to the client as a PNG image, but I also got the exception:
"ASP.NET The calling thread must be STA, because many UI components require this."
The 3 thread lines at the bottom is probably what can help you.
void SendExceptionAsPNG(Exception ex) {
Thread STAThread = new Thread(() => {
TextBlock TextBlock = new TextBlock();
TextBlock.Text = "Internal server error: " + ex.ToString();
TextBlock.TextWrapping = TextWrapping.WrapWithOverflow;
TextBlock.Foreground = new SolidColorBrush(System.Windows.Media.Colors.Red);
TextBlock.VerticalAlignment = VerticalAlignment.Top;
Border Border = new Border();
Border.BorderBrush = new SolidColorBrush(System.Windows.Media.Colors.Black);
Border.BorderThickness = new Thickness(2);
Border.Margin = new Thickness(20);
Border.Padding = new Thickness(20);
Border.Child = TextBlock;
Border.Width = 700;
Border.Height = 700;
Border.Arrange(new Rect(0, 0, 740, 740));
var RTB = new RenderTargetBitmap(740, 740, 96, 96, PixelFormats.Default);
RTB.Render(Border);
var PNGEncoder = new PngBitmapEncoder();
PNGEncoder.Frames.Add(BitmapFrame.Create(RTB));
Response.Clear();
Response.ContentType = "image/png";
using (MemoryStream MemoryStream = new MemoryStream()) {
PNGEncoder.Save(MemoryStream);
byte[] Bytes = MemoryStream.ToArray();
Response.OutputStream.Write(Bytes, 0, Bytes.Length);
}
Response.Flush();
Response.End();
});
STAThread.SetApartmentState(ApartmentState.STA);
STAThread.Start();
STAThread.Join();
}
I hope that helps.
Martin