[ASP.NET] Page_Load 에서 Response 종료하는 코드

2015. 2. 17. 12:04Coders

웹 코딩은, 전방(?)의 html, css 뿐만 아니라, 후방(Codebehind)의 C# 코딩과의 호출 시점 등의 차이로 인해 저 처럼 윈폼을 다루던 개발자들에게는 참 생소한 작업입니다.


기본 지식 없이 처음 웹 코딩을 접하는 분들이(저 처럼) 많이 실수하는 부분이 클라이언트에 페이지가 로드된 이후에도 Codebehind 단의 코딩, 메서드가 먹을 거라 착각하는 것이죠.


아, 올리려던 내용이랑 조금 엇나갔는데요, Classic ASP 코딩에서는 그냥 Response.Write, Response.End 하면 간단한 텍스트를 찍을 수 있는데, ASP.NET의 Page_Load 메서드에서 단순히 Response를 종료시키면 ThreadAbortException이 발생하게 됩니다.


다음은, 예외오류 없이 텍스트, html, xml, json 데이터를 찍을 수 있는 코드 입니다.

internal static void DrawResponseRaw(string contentType, string contentString)
{
	DrawResponseRaw(contentType, contentString, System.Text.Encoding.UTF8);
}

internal static void DrawResponseRaw(string contentType, string contentString, System.Text.Encoding encoding)
{
	contentString = contentString == null ? string.Empty : contentString;

	// "text/xml", "Application/json", "text/html"
	if (string.IsNullOrEmpty(contentString))
		contentType = "text/plain";	//비어 있으면 그냥 플레인

	HttpContext.Current.Response.Clear();

	//euc-kr 일 경우 처리
	if (encoding == Encoding.GetEncoding("ks_c_5601-1987"))
	{
		HttpContext.Current.Response.AddHeader("Cache-Control", "No-Cache");
		HttpContext.Current.Response.AddHeader("Expire", "0");
		HttpContext.Current.Response.AddHeader("Pragma", "No-Cache");
		HttpContext.Current.Response.Charset = "ks_c_5601-1987"; //euc-kr
	}

	HttpContext.Current.Response.ContentType = contentType;
	HttpContext.Current.Response.ContentEncoding = encoding;
	HttpContext.Current.Response.Write(contentString);

	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.
}