Asp.net Core WebApi 글로벌 예외 클래스
1. 전역 비정상 처리 클래스 중간부품 사용자 정의
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Xml.Serialization;
using UFX.Mall.EntityModel;
using UFX.Tools;
namespace UFX.Mall.WebApi
{
public class ExceptionHandlerMiddleWare
{
private readonly RequestDelegate next;
public ExceptionHandlerMiddleWare(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
if (exception == null) return;
await WriteExceptionAsync(context, exception).ConfigureAwait(false);
}
private static async Task WriteExceptionAsync(HttpContext context, Exception exception)
{
//
LogHelper.Error(exception.GetBaseException().ToString());
//
var response = context.Response;
//
if (exception is UnauthorizedAccessException)
response.StatusCode = (int)HttpStatusCode.Unauthorized;
else if (exception is Exception)
response.StatusCode = (int)HttpStatusCode.BadRequest;
response.ContentType = context.Request.Headers["Accept"];
if (response.ContentType.ToLower() == "application/xml")
{
await response.WriteAsync(Object2XmlString(ResultMsg.Failure(exception.GetBaseException().Message))).ConfigureAwait(false);
}
else
{
response.ContentType = "application/json";
await response.WriteAsync(JsonConvert.SerializeObject(ResultMsg.Failure(exception.GetBaseException().Message))).ConfigureAwait(false);
}
}
/// <summary>
/// Xml
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
private static string Object2XmlString(object o)
{
StringWriter sw = new StringWriter();
try
{
XmlSerializer serializer = new XmlSerializer(o.GetType());
serializer.Serialize(sw, o);
}
catch
{
//Handle Exception Code
}
finally
{
sw.Dispose();
}
return sw.ToString();
}
}
}
반환 값은 기본적으로 사용자 정의 클래스 ResultMsg로 포맷되어 있으며, 프로젝트의 요구에 따라 사용자 정의 실체를 되돌려줍니다
동시에 클라이언트가 필요로 하는 형식에 따라 자동으로 xml 또는 json으로 변환됩니다
2, configure 등록
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
// NLog
loggerFactory.AddNLog();
env.ConfigureNLog("nlog.config");
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
//
app.UseMiddleware(typeof(ExceptionHandlerMiddleWare));
app.UseMvc(); ;
}
3, 마무리, 모든 이상 처리 가능
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.