ASP.NET CORE 학습 튜 토리 얼 의 사용자 정의 이상 처리 상세 설명
전통 적 인 ASP.NET 은 이상 필 터 를 사용 하여 이상 을 처리 할 수 있 습 니 다.ASP.NET CORE 에 서 는 여러 개의 미들웨어 로 연 결 된 파이프 형식 으로 요청 을 처리 할 수 있 습 니 다.그러나 자주 사용 하 는 5 대 필 터 는 보존 되 고 이상 필터 로 이상 을 처리 할 수 있 습 니 다.그러나 이상 필 터 는 MVC 미들웨어 이외 의 이상 을 처리 할 수 없습니다.전체적인 통일 을 위해 고려 합 니 다.미들웨어 처리 이상 이 더욱 적합 하 다.
왜 사용자 정의 이상 미들웨어 를 선택 합 니까?
먼저 ASP.NET CORE 에 내 장 된 세 개의 이상 처리 미들웨어 Developer ExceptionPageMiddleware,ExceptionHandler Middleware,Status CodePageMiddleware 를 살 펴 보 겠 습 니 다.
1.DeveloperExceptionPageMiddleware
민감 한 정보 가 포함 되 어 있 기 때문에 개발 환경 에 만 적합 합 니 다.
2.ExceptionHandlerMiddleware(장 신 블 로그:https://www.jb51.net/article/153926.htm)
500 오류 만 처리
3.StatusCodePagesMiddleware(장 신 블 로그:https://www.jb51.net/article/153931.htm)
400-599 사이 의 오 류 를 처리 할 수 있 지만 Response 에 내용 을 포함 할 수 없습니다(ContentLength=0&&ContentType=null,실험 을 통 해 mvc 에서 이상 을 포착 하지 못 했 습 니 다)
Exception Handler Middleware 와 Status CodePagesMiddleware 의 각각의 제한 조건 때문에 둘 을 조합 해서 사용 해 야 한다.이에 비해 사용자 정의 미들웨어 가 더욱 유연 하고 각종 오류 상 태 를 통일 적 으로 처리 할 수 있 으 며 설정 에 따라 처리 방식 을 결정 할 수 있 습 니 다.
CustomExceptionMiddleWare
우선 이상 미들웨어 설정 클래스 를 설명 합 니 다.
/// <summary>
 ///          
 /// </summary>
 public class CustomExceptionMiddleWareOption
 {
 public CustomExceptionMiddleWareOption(
  CustomExceptionHandleType handleType = CustomExceptionHandleType.JsonHandle,
  IList<PathString> jsonHandleUrlKeys = null,
  string errorHandingPath = "")
 {
  HandleType = handleType;
  JsonHandleUrlKeys = jsonHandleUrlKeys;
  ErrorHandingPath = errorHandingPath;
 }
 /// <summary>
 ///       
 /// </summary>
 public CustomExceptionHandleType HandleType { get; set; }
 /// <summary>
 /// Json     Url   
 /// <para> HandleType=Both   </para>
 /// </summary>
 public IList<PathString> JsonHandleUrlKeys { get; set; }
 /// <summary>
 ///       
 /// </summary>
 public PathString ErrorHandingPath { get; set; }
 }
 /// <summary>
 ///       
 /// </summary>
 public enum CustomExceptionHandleType
 {
 JsonHandle = 0, //Json    
 PageHandle = 1, //      
 Both = 2  //  Url       
 }이상 미들웨어 를 설명 하 는 구성원
/// <summary>
 ///       
 /// </summary>
 private RequestDelegate _next;
 /// <summary>
 ///     
 /// </summary>
 private CustomExceptionMiddleWareOption _option;
 /// <summary>
 ///           
 /// </summary>
 private IDictionary<int, string> exceptionStatusCodeDic;
 public CustomExceptionMiddleWare(RequestDelegate next, CustomExceptionMiddleWareOption option)
 {
  _next = next;
  _option = option;
  exceptionStatusCodeDic = new Dictionary<int, string>
  {
  { 401, "      " },
  { 404, "      " },
  { 403, "     " },
  { 500, "          " }
  //        
  };
 }이상 미들웨어 주요 논리
public async Task Invoke(HttpContext context)
 {
  Exception exception = null;
  try
  {
  await _next(context); //            
  }
  catch (Exception ex)
  {
  context.Response.Clear(); 
  context.Response.StatusCode = 500; //        ,       
  exception = ex;
  }
  finally
  {
  if (exceptionStatusCodeDic.ContainsKey(context.Response.StatusCode) && 
   !context.Items.ContainsKey("ExceptionHandled")) //     
  {
   var errorMsg = string.Empty;
   if (context.Response.StatusCode == 500 && exception != null)
   {
   errorMsg = $"{exceptionStatusCodeDic[context.Response.StatusCode]}\r
{(exception.InnerException != null ? exception.InnerException.Message : exception.Message)}";
   }
   else
   {
   errorMsg = exceptionStatusCodeDic[context.Response.StatusCode];
   }
   exception = new Exception(errorMsg);
  }
  if (exception != null)
  {
   var handleType = _option.HandleType;
   if (handleType == CustomExceptionHandleType.Both) //  Url           
   {
   var requestPath = context.Request.Path;
   handleType = _option.JsonHandleUrlKeys != null && _option.JsonHandleUrlKeys.Count(
    k => context.Request.Path.StartsWithSegments(k, StringComparison.CurrentCultureIgnoreCase)) > 0 ?
    CustomExceptionHandleType.JsonHandle :
    CustomExceptionHandleType.PageHandle;
   }
   
   if (handleType == CustomExceptionHandleType.JsonHandle)
   await JsonHandle(context, exception);
   else
   await PageHandle(context, exception, _option.ErrorHandingPath);
  }
  }
 }
 /// <summary>
 ///        
 /// </summary>
 /// <param name="ex"></param>
 /// <returns></returns>
 private ApiResponse GetApiResponse(Exception ex)
 {
  return new ApiResponse() { IsSuccess = false, Message = ex.Message };
 }
 /// <summary>
 ///     :  Json  
 /// </summary>
 /// <param name="context"></param>
 /// <param name="ex"></param>
 /// <returns></returns>
 private async Task JsonHandle(HttpContext context, Exception ex)
 {
  var apiResponse = GetApiResponse(ex);
  var serialzeStr = JsonConvert.SerializeObject(apiResponse);
  context.Response.ContentType = "application/json";
  await context.Response.WriteAsync(serialzeStr, Encoding.UTF8);
 }
 /// <summary>
 ///     :    
 /// </summary>
 /// <param name="context"></param>
 /// <param name="ex"></param>
 /// <param name="path"></param>
 /// <returns></returns>
 private async Task PageHandle(HttpContext context, Exception ex, PathString path)
 {
  context.Items.Add("Exception", ex);
  var originPath = context.Request.Path;
  context.Request.Path = path; //             
  try
  {
  await _next(context); 
  }
  catch { }
  finally
  {
  context.Request.Path = originPath; //        
  }
 }확장 클래스 를 사용 하여 미들웨어 등록 을 진행 합 니 다.
public static class CustomExceptionMiddleWareExtensions
 {
 public static IApplicationBuilder UseCustomException(this IApplicationBuilder app, CustomExceptionMiddleWareOption option)
 {
  return app.UseMiddleware<CustomExceptionMiddleWare>(option);
 }
 }Startup.cs 의 Configuref 방법 에 이상 미들웨어 를 등록 합 니 다.
 app.UseCustomException(new CustomExceptionMiddleWareOption(
   handleType: CustomExceptionHandleType.Both, //  url         
   jsonHandleUrlKeys: new PathString[] { "/api" },
   errorHandingPath: "/home/error"));다음은 테스트 를 진행 하 겠 습 니 다.먼저 페이지 를 뛰 어 넘 을 캡 처 되 지 않 은 이상 을 모 의 하 겠 습 니 다.
 방문/home/about 결과
 접근/home/test 결과(이 주 소 는 존재 하지 않 습 니 다)
 OK 이상 페이지 전환 방식 테스트 가 완료 되 었 습 니 다.그 다음 에 우 리 는 통 일 된 형식(json)의 이상 처 리 를 테스트 합 니 다.마찬가지 로 캡 처 되 지 않 은 이상 을 먼저 모 의 합 니 다.
 방문/api/token/gettesterror 결과
 /api/token/test 에 접근 한 결과(이 주 소 는 존재 하지 않 습 니 다)
 /api/token/getvalue 에 접근 한 결과(이 인 터 페 이 스 는 인증 이 필요 합 니 다)
 테스트 가 완료 되 었 습 니 다.페이지 전환 과 통 일 된 형식 반환 에 문제 가 없습니다.사용자 정의 이상 미들웨어 가 예상 한 대로 작 동 되 었 습 니 다.
주의해 야 할 것 은 사용자 정의 미들웨어 가 모든 HTTP 요청 에 응답 하기 때문에 처리 논 리 를 간소화 하여 불필요 한 성능 문제 가 발생 하지 않도록 해 야 한 다 는 것 이다.
총결산
이상 은 이 글 의 전체 내용 입 니 다.본 논문 의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 참고 학습 가치 가 있 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 댓 글 을 남 겨 주 셔 서 저희 에 대한 지지 에 감 사 드 립 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Tailwind를 ASP.NET Core 프로젝트에 통합우리는 을 사용합니다. 에서 코드를 찾을 수 있습니다. 면도기 페이지 구조를 추가합니다. "node_modules"가 설치되었습니다. "tailwind.config.js"파일이 생성되었습니다. 모든 .razor 및 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.