I'm trying to use this Converting between RTF and HTML library from MSDN to convert some RTF text to HTML. The jist of my setup is an AJAX call from JavaScript to a C# handler which calls this MarkupConverter
library to do the conversion, then write back the HTML.
Here's my JavaScript:
$.ajax({
type: "POST",
url: "MyHandler.ashx",
data: richTextData,
success: function (html) {
alert('success, html: ' + html);
},
error: function (msg) {
alert("error: " + msg);
}
});
And the code from my handler, which is also very simple:
public void ProcessRequest(HttpContext context)
{
if (context.Request.Form.Count > 0)
{
string rtf = context.Request.Form[0];
string html = "";
if (rtf != "")
{
markupConverter = new MarkupConverter.MarkupConverter();
html = markupConverter.ConvertRtfToHtml(rtf);
}
if (html != "")
{
context.Response.ContentType = "text/html";
context.Response.Write(html);
}
else
{
context.Response.ContentType = "text/plain";
context.Response.Write("Error from RTF2HTML");
}
}
}
The problem is, every time this runs, an Exception is thrown because the RichTextBox
control is getting created on a background thread:
[InvalidOperationException: The calling thread must be STA, because many UI components require this.]
System.Windows.Input.InputManager..ctor() +11032206
System.Windows.Input.InputManager.GetCurrentInputManagerImpl() +125
System.Windows.Input.KeyboardNavigation..ctor() +185
System.Windows.FrameworkElement.EnsureFrameworkServices() +109
System.Windows.FrameworkElement..ctor() +504
System.Windows.Controls.Control..ctor() +87
System.Windows.Controls.RichTextBox..ctor(FlowDocument document) +56
MarkupConverter.RtfToHtmlConverter.ConvertRtfToXaml(String rtfText) +67 MarkupConverter.RtfToHtmlConverter.ConvertRtfToHtml(String rtfText) +23 MyHandler.ProcessRequest(HttpContext context) +416
I thought maybe because the AJAX call is asychronous, the call is getting placed on a background thread. So I changed it to this:
var postText = $.ajax({
type: "POST",
url: "RTF2HTML.ashx",
data: textData,
async: false
}).responseText;
alert(postText);
But even still when I check the current thread in my handler:
context.Response.Write("thread: " + System.Threading.Thread.CurrentThread.GetApartmentState().ToString());
It still returns MTA.
Is there a way to hook into the main STA thread, or will I have to create a new thread and specify STA? If that's the case, how can I set the callback function up to return my HTML the way Response.Write
currently does?