Skip to main content
 首页 » 编程设计

c#之当我使用带有 Silverlight 4.0 的 WebClient 调用 aspx 页面时,无法执行 Response.Redirect

2024年01月12日3252php

我正在从事 Silverlight 项目。 当我将 jpg 图片保存到内存流中以保存它时 进入 Context.InputStream,它工作正常。 我正在调用一个将上传线程上传到服务器的 aspx 页面。

但是当上传完成或失败时,我无法执行“response.redirect”或“server.transfer”。 是因为我使用 WebClient 从 Silverlight 调用我的 aspx 页面吗?

请在下面的 Silverlight 中找到代码:

 private void UploadFile(string fileName, Stream data){  
 
 UriBuilder ub = new UriBuilder("http://localhost:52544/WebForm1.aspx"); 
 
//add a parameter filename  into the queryString 
 
ub.Query = string.Format("filename={0}", fileName); 
 
WebClient c = new WebClient(); 
 
c.OpenWriteCompleted += (sender, e) => 
   { 
 
      PushData(data, e.Result); 
      e.Result.Close(); 
      data.Close(); 
   }; 
c.OpenWriteAsync(ub.Uri); 
} 

在aspx页面上,我有这段代码

protected void Page_Load(object sender, EventArgs e) 
        { 
            try 
            {              
                // get the filename 
 
                string filename = Request.QueryString["filename"].ToString(); 
 
                // create a file on the server dir 
 
                using (FileStream fs = File.Create(Server.MapPath("~/AppData/" + filename))) 
                { 
                    SaveFile(Request.InputStream, fs); 
                } 
 
                    Response.Redirect("uploadOk.aspx", true); 
                } 
                catch (Exception ex) 
                { 
 
                } 
 
 
        } 
 
 
        private bool SaveFile(Stream stream, FileStream fs) 
        { 
            bool isSaved = true; 
            byte[] buffer = new byte[4096]; 
            int bytesRead; 
            try 
            { 
                // copy the stream into the file 
 
                while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0) 
                { 
                    fs.Write(buffer, 0, bytesRead); 
                } 
                isSaved = true; 
            } 
            catch (Exception e) 
            { 
                isSaved = false; 
            } 
            return isSaved; 
        } 
    } 

我也尝试过 response.redirection("uploadOk.aspx",false) 但它不起作用。 我收到以下异常“[System.Threading.ThreadAbortException] = {无法评估 表达式,因为代码已优化或 native 框架位于调用堆栈的顶部。}”

您知道我如何使用 WebClient 进行重定向吗?

提前致谢

请您参考如下方法:

我认为您的问题是上传失败,但因为它在不同的线程上,SL 没有显示正确的错误。尝试添加代码以在错误发生时记录错误并查看错误是什么。您也可以在服务器上执行此操作。

我怀疑问题是标题已经写好了,所以它不能重定向。

试试这个,因为我认为问题是 100-continue:

 c.Headers.Add( HttpRequestHeader.KeepAlive, "false"); 
 c.Headers.Add(HttpRequestHeader.Expect, "");