Context.Response.End()和Thread正在中止

Tom*_*mas 24 asp.net

我试图关闭响应使用Context.Response.End但收到错误"Thread was being aborted".

如何在不触发异常的情况下正确关闭响应?

try {
   Context.Response.Clear();
   Context.Response.ContentType = "text/html"; 
   //Context.Response.ContentType = "application/json";
   JsonObjectCollection collection = new JsonObjectCollection();
   collection.Add(new JsonNumericValue("resultcode", 1));
   collection.Add(new JsonStringValue("sourceurl", exchangeData.cUrl));
   collection.Add(new JsonStringValue("filename", fileName));
   collection.Add(new JsonStringValue("filesize", fileSize));
   collection.Add(new JsonStringValue("fileurl", Common.GetPDFURL + outputFileName));
   JsonUtility.GenerateIndentedJsonText = true;
   Context.Response.Write(collection);
  try {
     Context.Response.End();
  } catch (ThreadAbortException exc) {
     // This should be first catch block i.e. before generic Exception
     // This Catch block is to absorb exception thrown by Response.End
  }
} catch (Exception err) {

}
Run Code Online (Sandbox Code Playgroud)

由我自己解决,代码应该看起来像

try {
  Context.Response.End();
} catch (ThreadAbortException err) {

}
catch (Exception err) {
}
Run Code Online (Sandbox Code Playgroud)

Joh*_*sch 26

你有没有特别的原因而不是使用context.ApplicationInstance.CompleteRequest()

此方法将短路ASP.NET管道(EndRequest事件除外)而不抛出,ThreadAbortException因此您不需要额外try/ catch块,并且您还将体验到更好的性能.

  • 我刚试过这个(聚会有点晚了)。它似乎没有正常工作:当然它没有抛出 Response.End() 抛出的异常,但它确实导致 .aspx 页面的内容被附加到我已经写入 Response.OutputStream 的内容中. 一种选择可能是 .aspx 文件中没有内容,但我已经使用它来显示错误内容。 (2认同)

小智 10

尝试response.OutputStream.Close(); 而不是response.End(); 我会帮你的!