0

我想实现这个功能:当接收到一个http请求时,然后创建一个新的窗体,并等待用户输入响应文本并写入http响应流。问题是,即使我使用 Action<> 委托,我也无法将响应文本写入线程中的流。像这样的一些代码:

public partial class MainWindow : Window
{
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        //startup web server 
        Dispatcher.BeginInvoke(new Action(Start));
    }

    private void Start()
    {
        var server = new HttpServer();
        try
        {
            server.EndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 80);
            server.Start();
            server.RequestReceived += DataProcess;
        }
        catch (Exception ex)
        {
            return;
        }
    }

    private void DataProcess(object sender, HttpRequestEventArgs e)
    {
        //create a new window in which user can input the response for the http request e.
        var pw = (PrivateWindow)Dispatcher.Invoke(new Func<HttpRequestEventArgs, PrivateWindow>(CreatePrivateWindow), e);
    }

    public PrivateWindow CreatePrivateWindow(string windowKey, HttpRequestEventArgs e)      
    {
        var pw = new PrivateWindow(); 
        pw.httpRequest = e;//pass the stream to thread here.       
        windows.Add(pw);
        return pw;    
    }
}

public partial class PrivateWindow : Window
{
    private void btnSendMessage_Click(object sender, RoutedEventArgs e)
    {
        string messageText = new TextRange(txtWriteMessage.Document.ContentStart, txtWriteMessage.Document.ContentEnd).Text.Trim(); 
        //write the response in thread           
        Dispatcher.BeginInvoke(new Action<HttpRequestEventArgs, string>(WriteToStream), httpRequest, messageText);
    }
    private void WriteToStream(HttpRequestEventArgs e, string str)
    {
        //**here occurs "stream can not be written" error.** 
        using (var writer = new StreamWriter(e.Response.OutputStream))
        {
            writer.Write(str);
        }
    }
} 
4

0 回答 0