[C#] WebService .asmx 오류 전역 (예외)처리

2019. 6. 17. 17:19· .Net Framework Standard

SoapExtension을 상속받아 오류를 전역 단에서 예외처리 하는 부분입니다.

WebService 2.0 인 .asmx는 http 500 에러가 발생할 경우 Global.aspx의 Application_Error 에서 캡쳐가 선행되지 않고 클라이언트로 내려 갑니다.

가끔 보안상의 이유로 오류 세부 내용을 감춰야 하는 등의 처리나 별도 로그를 남기기 위해 사용됩니다.

 

※ SoapExceptionHandler.cs

    public class SoapExceptionHandler : SoapExtension
	{
		Stream _oldStream;
		Stream _newStream;

		public override Stream ChainStream(Stream stream)
		{
			_oldStream = stream;
			_newStream = new MemoryStream();
			return _newStream;
		}

		public override void ProcessMessage(SoapMessage message)
		{
			if (message.Stage == SoapMessageStage.AfterSerialize)
			{
				_newStream.Position = 0;

				if (message.Exception != null && message.Exception.InnerException != null)
				{
					// 오류가 있을경우
					InsertDetailExceptionStream(message.Exception.InnerException);
				}
				else
				{
					CopyStream(_newStream, _oldStream);
				}
			}
			else if (message.Stage == SoapMessageStage.BeforeDeserialize)
			{
				CopyStream(_oldStream, _newStream);
				_newStream.Position = 0;
			}
		}

		private void CopyStream(Stream from, Stream to)
		{
			TextReader reader = new StreamReader(from);
			TextWriter writer = new StreamWriter(to);
			writer.WriteLine(reader.ReadToEnd());
			writer.Flush();
		}

		private void InsertDetailExceptionStream(Exception exception)
		{
			XmlDocument doc = new XmlDocument();
			doc.Load(_newStream);
			
			XmlNode faultstringNode = doc.SelectSingleNode("//faultstring");
			faultstringNode.InnerText = "오류 입니다.~!";
			
			XmlNode detail = doc.SelectSingleNode("//detail");
			detail.InnerText = "오류 세부 내용 입니다.";


			XmlWriter writer = new XmlTextWriter(_oldStream, Encoding.UTF8);
			doc.WriteTo(writer);
			writer.Flush();
		}

		#region Not Used
		public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
		{
			return null;
		}

		public override object GetInitializer(Type serviceType)
		{
			return null;
		}

		public override void Initialize(object initializer)
		{
		}
		#endregion
	}

※ ExceptionHandlingAttribute.cs

	[AttributeUsage(AttributeTargets.Method)]
	public class ExceptionHandlingAttribute : SoapExtensionAttribute
	{
		public override Type ExtensionType { get { return typeof(SoapExceptionHandler); } }
		public override int Priority { get { return 0; } set { } }
	}

 

※ 사용방법

        [ExceptionHandling] //Attribute 로 사용
        [WebMethod(EnableSession = true)]
        public byte[] GetLog()
        {
            if (isSession())
            {
                return Compress.DataSet(Log.Log.GetLog());
            }

            return null;
        }

        [ExceptionHandling] //Attribute 로 사용
        [WebMethod(EnableSession = true)]
        public bool SetLog(string value1, string value2, string value3, string value4, string value5, string value6, string value7)
        {
            if (isSession())
            {
                return Log.Log.SetLog(value1.Decrypt(), value2.Decrypt(), value3.Decrypt(), value4.Decrypt(), value5.Decrypt(), value6.Decrypt(), value7.Decrypt());
            }
            else
            {
                return false;
            }

        }

 

 

출처 - https://haacked.com/archive/2005/06/29/ExceptionInjectionUsingCustomSoapExtension.aspx/

'.Net Framework Standard' 카테고리의 다른 글

기본 연결이 닫혔습니다. SSL/TLS 보안 채널에 대한 트러스트 관계를 설정할 수 없습니다. ( fit. Let's Encrypt )  (0) 2025.02.07
[C#] 오류 처리 - TLS 버전  (0) 2022.10.21
[ClickOnce] 배포 후 업데이트 오류시- 폴더 삭제 혹은 Registry 삭제  (0) 2018.08.28
Visual Studio에서 찾기 / 바꾸기 기능에서 정규식 사용 방법..  (1) 2018.04.06
Visual Studio 2012 Web Project Debuging 시 IIS Express 64bit 사용하기  (0) 2017.08.11
'.Net Framework Standard' 카테고리의 다른 글
  • 기본 연결이 닫혔습니다. SSL/TLS 보안 채널에 대한 트러스트 관계를 설정할 수 없습니다. ( fit. Let's Encrypt )
  • [C#] 오류 처리 - TLS 버전
  • [ClickOnce] 배포 후 업데이트 오류시- 폴더 삭제 혹은 Registry 삭제
  • Visual Studio에서 찾기 / 바꾸기 기능에서 정규식 사용 방법..
달빛에취하다
달빛에취하다
개발 관련 자료
달빛에취하다
삽질은 내 운명
달빛에취하다
전체
오늘
어제
GUEST
WRITE
ADMIN
  • 분류 전체보기 (72)
    • .Net Framework Standard (8)
      • WindowsApplication (7)
      • Silverlight (0)
      • ASP.NET (3)
      • Component (5)
    • .Net Core (3)
      • gRPC (2)
    • Database (8)
      • MSSQL (8)
      • MySQL (0)
      • Oracle (0)
    • Server (28)
      • Windows Server (15)
      • Linux (7)
      • NAS (1)
    • Etc (7)
      • Utility (3)

블로그 메뉴

  • 홈
  • 방명록

공지사항

인기 글

태그

  • hyper-v
  • ubuntu
  • DevExpress
  • docker
  • TLS
  • mssql
  • Fiddler
  • sql
  • 인증서
  • VisualStudio
  • m365
  • Microsoft365
  • TreeList
  • C#
  • IIS
  • TLS1.2
  • url rewrite
  • powershell
  • ARR
  • reverse proxy
  • reverseproxy
  • ServicePointManager.SecurityProtocol
  • GRPC
  • https
  • ad
  • Windows Server
  • ssl
  • ClickOnce
  • Windows
  • office365

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.2
달빛에취하다
[C#] WebService .asmx 오류 전역 (예외)처리
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.