응답을 피하는 방법.종료() Excel 파일 다운로드 중 "스레드가 중단되었습니다." 예외
저는 제 데이터셋을 엑셀로 변환해서 그 엑셀을 다운받으려고 했습니다.필요한 엑셀 파일을 받았습니다.하지만 시스템.스레드화.ThreadAbortException은 엑셀을 다운로드할 때마다 발생했습니다.이 문제를 해결하는 방법은 무엇입니까?제발 도와주세요...
나는 내 aspx 화면에서 이 메소드를 부릅니다.또한 이 방법에 의해 던져진 동일한 예외가 있습니다.
저는 많은 aspx 화면에서 public void ExportDataSet(DataSets) 기능을 호출하고 런타임에 발생하는 예외에 대한 오류 로거 메서드를 유지하고 있습니다. 예외는 .txt 파일에 기록됩니다.따라서 동일한 예외가 모든 aspx 화면의 txt 파일에 기록됩니다.메서드 선언 클래스 파일에서 aspx로 이 예외를 슬로우하지 않도록 하고 싶습니다.단순히 메서드 선언 클래스 파일 자체에서 이 예외를 처리하고 싶습니다.
ASPX 파일 메서드 호출: excel.데이터 집합 내보내기(dsExcel);
메서드 정의:
public void ExportDataSet(DataSet ds)
{
try
{
string filename = "ExcelFile.xls";
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Charset = "";
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
GridView dg = new GridView();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
// response.Write(style);
response.Write(sw.ToString());
response.End(); // Exception was Raised at here
}
}
}
catch (Exception ex)
{
string Err = ex.Message.ToString();
EsHelper.EsADLogger("HOQCMgmt.aspx ibtnExcelAll_Click()", ex.Message.ToString());
}
finally
{
}
}
나는 온라인으로 조사했고 그것을 보았습니다.Response.End()항상 예외를 발생시킵니다.
대체:HttpContext.Current.Response.End();
사용:
HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
HttpContext.Current.Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client.
HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.
이것은 제가 처리하는 데 도움이 되었습니다.Thread was being aborted 예를 들어옵니다.
try
{
//Write HTTP output
HttpContext.Current.Response.Write(Data);
}
catch (Exception exc) {}
finally {
try
{
//stop processing the script and return the current result
HttpContext.Current.Response.End();
}
catch (Exception ex) {}
finally {
//Sends the response buffer
HttpContext.Current.Response.Flush();
// Prevents any other content from being sent to the browser
HttpContext.Current.Response.SuppressContent = true;
//Directs the thread to finish, bypassing additional processing
HttpContext.Current.ApplicationInstance.CompleteRequest();
//Suspends the current thread
Thread.Sleep(1);
}
}
만약 당신이 다음 코드를 대신 사용한다면.HttpContext.Current.Response.End()얻게 될 것입니다Server cannot append header after HTTP headers have been sent예외.
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.SuppressContent = True;
HttpContext.Current.ApplicationInstance.CompleteRequest();
도움이 되길 바랍니다.
응답을 이동합니다.끝()에서 시도/캐치 및 사용 블록 외부로 이동합니다.
요청의 나머지 부분을 무시하기 위해 예외를 발생시키는 것으로 간주됩니다. 당신은 그것을 감지하지 말았어야 했습니다.
bool endRequest = false;
try
{
.. do stuff
endRequest = true;
}
catch {}
if (endRequest)
Resonse.End();
다음과 같은 질문인 것 같습니다.
ASP일 때.NET 시스템.Web.HttpResponse.End()가 호출되고, 현재 스레드가 중단됩니까?
그래서 그것은 설계에 의한 것입니다.해당 예외에 대한 캐치를 추가하고 우아하게 "무시"해야 합니다.
그냥 놔둬요
Response.End();
시도 블록 내가 아니라 최종 블록 내에서.
이것은 나에게 효과가 있었습니다!!!
다음과 같은 (예외) 코드 구조에 문제가 있었습니다.
...
Response.Clear();
...
...
try{
if (something){
Reponse.Write(...);
Response.End();
return;
}
some_more_code...
Reponse.Write(...);
Response.End();
}
catch(Exception){
}
finally{}
그리고 그것은 예외를 던집니다.응답 후 실행해야 할 코드/작업이 있는 경우 예외가 발생한 것 같습니다.End(); . 제 경우 추가 코드는 반품 그 자체였습니다.
제가 방금 반응을 옮겼을 때.끝(); 마지막 블록으로(그리고 그 자리에 반환을 남겼습니다. 즉, 시도 블록의 나머지 코드를 건너뛰고 마지막 블록으로 점프합니다(포함된 함수를 종료하는 것이 아니라).) 예외가 발생하지 않습니다.
다음은 정상적으로 작동합니다.
...
Response.Clear();
...
...
try{
if (something){
Reponse.Write(...);
return;
}
some_more_code...
Reponse.Write(...);
}
catch(Exception){
}
finally{
Response.End();
}
나는 오직 일만 합니다.
HttpContext입니다.현재의.어플사례.요청 완료().
https://stackoverflow.com/a/21043051/1828356
반응을 제외한 특수 캐치 블록을 사용합니다.종료() 메서드
{
...
context.Response.End(); //always throws an exception
}
catch (ThreadAbortException e)
{
//this is special for the Response.end exception
}
catch (Exception e)
{
context.Response.ContentType = "text/plain";
context.Response.Write(e.Message);
}
또는 응답을 제거합니다.파일 처리기를 작성하는 경우 종료()
Update Panel에서 링크 버튼을 제거하고 Response에 대해서도 설명했습니다.끝() 성공!!!
이것은 문제가 아니라 의도적인 것입니다.근본 원인은 마이크로소프트 지원 페이지에 설명되어 있습니다.
응답.End 메서드는 페이지 실행을 종료하고 응용 프로그램의 이벤트 파이프라인에 있는 Application_EndRequest 이벤트로 실행을 이동합니다.반응을 따르는 코드 행입니다.종료가 실행되지 않았습니다.
제공되는 솔루션은 다음과 같습니다.
응답용.끝으로 HttpContext를 호출합니다.현재의.어플사례.응답 대신 요청 메서드를 완료합니다.End - 코드 실행을 Application_EndRequest 이벤트로 우회합니다.
링크는 다음과 같습니다. https://support.microsoft.com/en-us/help/312629/prb-threadabortexception-occurs-if-you-use-response-end--response-redi
My JSON file-download was solved by using the blow code:
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
But Excel file-download was solved by the below way:
try {
.....
}
catch (System.IO.IOException iex)
{
throw (iex);
}
catch (System.Threading.ThreadAbortException)
{
throw new Exception("ABORTED");//make a custom msg here and catch it
//where required to continue the rest
//of the work flow.
}
catch (Exception exx)
{
throw (exx);
}
finally
{
....
}
응답에 대한 오류입니다.END(); 이는 당신이 asp 업데이트 패널이나 javascript를 사용하는 컨트롤을 사용하고 있기 때문입니다. javascript나 scriptmanager나 scripting 없이 asp나 html에서 네이티브 컨트롤을 사용하고 다시 시도하십시오.
코드 뒤에 있는 코드를 호출하는 버튼을 포스트백 컨트롤로 등록하는 데 도움이 되었습니다.
protected void Page_Init(object sender, EventArgs e)
{
ScriptManager.GetCurrent(this.Page).RegisterPostBackControl(btnMyExport);
}
알아요, 이것은 오래된 질문이지만, 여기서 해결책을 찾을 수 없었습니다.몇 번 시도해 본 결과, "<asp:UpdatePanel"이 그 이유였습니다.
그것들을 제거한 후에는 이전과 같이 모든 것이 정상적으로 작동합니다.
response.end보다 먼저 클라이언트에 대한 응답을 플러시합니다.
그래서 아래에 언급된 코드를 사용합니다.response.End();
response.Flush();
위의 변경 사항을 모두 사용했지만 웹 애플리케이션에서 동일한 문제가 발생했습니다.
그런 다음 호스팅 공급업체에 문의하여 HTTP 또는 ISP/네트워크를 통해 파일 전송을 차단하는 소프트웨어나 바이러스 백신이 있는지 확인해 달라고 요청했습니다.
서버 설정을 확인하고 서버에 대한 "데이터 센터 공유 방화벽"을 우회하여 이제 응용 프로그램에서 파일을 다운로드할 수 있습니다.
이 대답이 누군가에게 도움이 되기를 바랍니다.이것이 저에게 효과가 있었던 것입니다.
이유를 찾았어요.업데이트 패널을 제거하면 정상적으로 작동합니다!
이 솔루션을 권장합니다.
사용 안 함
response.End();이 글로벌 변수 선언:
bool isFileDownLoad;당신의 바로 다음에
(response.Write(sw.ToString());) set ==> isFileDownLoad = true;다음과 같이 렌더를 재정의합니다.
/// AEG : Very important to handle the thread aborted exception override protected void Render(HtmlTextWriter w) { if (!isFileDownLoad) base.Render(w); }
저는 다음이 더 잘 작동한다는 것을 발견했습니다.
private void EndResponse()
{
try
{
Context.Response.End();
}
catch (System.Threading.ThreadAbortException err)
{
System.Threading.Thread.ResetAbort();
}
catch (Exception err)
{
}
}
언급URL : https://stackoverflow.com/questions/20988445/how-to-avoid-response-end-thread-was-being-aborted-exception-during-the-exce
'programing' 카테고리의 다른 글
| 여러 비동기 작업을 실행하고 모든 작업이 완료될 때까지 대기 (0) | 2023.05.04 |
|---|---|
| 파일을 세는 bash 명령어가 있습니까? (0) | 2023.05.04 |
| Swift에서 유형이 다른 Superclass 속성을 재정의하는 중 (0) | 2023.04.29 |
| ASP에서 최대 업로드 파일 크기를 늘리는 방법.NET? (0) | 2023.04.29 |
| 기존 Excel 값에 선행 0/0을 특정 길이로 추가 (0) | 2023.04.29 |