Silverlight中的HTTP POST请求

时间:2011-06-17 10:17:14

标签: c# silverlight http post request

我正在开发一个Silverlight应用程序,它有一个Form,应该使用POST方法将表单数据发送到PHP页面。

我正在使用以下代码,它给了我一个安全异常。我认为这是一个跨域错误。我也检查了localhost上的视图,但是dint工作。 SOS

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("http://localhost/wb/cam.php", UriKind.Absolute));
                request.Method = "POST";
                // don't miss out this  
                request.ContentType = "application/x-www-form-urlencoded";
                request.BeginGetRequestStream(new AsyncCallback(RequestReady), request);  

    void RequestReady(IAsyncResult asyncResult)  
{

    HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;  
    Stream stream = request.EndGetRequestStream(asyncResult);  

    // Hack for solving multi-threading problem  
    // I think this is a bug  
    this.Dispatcher.BeginInvoke(delegate()  
    {  
        // Send the post variables  
        StreamWriter writer = new StreamWriter(stream);  
        writer.WriteLine("imgdata="+textBox1.Text);  
        writer.Flush();  
        writer.Close();  

        request.BeginGetResponse(new AsyncCallback(ResponseReady), request);  
    });  
}  

// Get the Result  
void ResponseReady(IAsyncResult asyncResult)
{
    try
    {
        HttpWebRequest request = asyncResult.AsyncState as HttpWebRequest;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

        this.Dispatcher.BeginInvoke(delegate()
        {
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            // get the result text  
            string result = reader.ReadToEnd();
        });
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}  

private void OnCaptureImageCompleted(object sender, CaptureImageCompletedEventArgs e)
{
            btnSnapshot.IsEnabled = true;
            webCamVRect.Background = new ImageBrush {ImageSource = e.Result};
        }

private void button1_Click(object sender, RoutedEventArgs e)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("http://localhost/wb/cam.php", UriKind.Absolute));
    request.Method = "POST";
    // don't miss out this  
    request.ContentType = "application/x-www-form-urlencoded";
    request.BeginGetRequestStream(new AsyncCallback(RequestReady), request);

}

1 个答案:

答案 0 :(得分:0)

您需要将clientaccesspolicy.xml添加到正在接收请求的服务器的根目录。还要注意虚拟路径,因为有时clientaccesspolicy会被放入虚拟路径而不是根目录中。祝你好运!