From ac0e7c830a08ab1285524fb8408dda3c3bae7cc7 Mon Sep 17 00:00:00 2001 From: "DESKTOP-M4V1LH5\\Jin" Date: Wed, 16 May 2018 23:36:49 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0webapi=20=E9=94=99=E8=AF=AF?= =?UTF-8?q?=E7=BB=9F=E4=B8=80=E8=BF=94=E5=9B=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Common/WebAPIHandleErrorAttribute.cs | 26 +++++++++++++++++++ .../Controllers/api/APIBaseController.cs | 2 ++ COMCMS.Web/Controllers/api/IndexController.cs | 10 +++++++ 3 files changed, 38 insertions(+) create mode 100644 COMCMS.Web/Common/WebAPIHandleErrorAttribute.cs diff --git a/COMCMS.Web/Common/WebAPIHandleErrorAttribute.cs b/COMCMS.Web/Common/WebAPIHandleErrorAttribute.cs new file mode 100644 index 0000000..87c3f42 --- /dev/null +++ b/COMCMS.Web/Common/WebAPIHandleErrorAttribute.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Net; +using Microsoft.AspNetCore.Mvc.Filters; +using NewLife.Log; +using Microsoft.AspNetCore.Mvc; +using COMCMS.Web.Controllers.api; + +namespace COMCMS.Web.Common +{ + public class WebAPIHandleErrorAttribute : ExceptionFilterAttribute + { + public override void OnException(ExceptionContext context) + { + context.HttpContext.Request.ContentType = "application/json"; + context.HttpContext.Request.Headers["Accept"] = "application/json"; + ReJSON model = new ReJSON(); + model.code = 5001; + model.message = "执行错误:"+ context.Exception.Message; + context.Result = new JsonResult(model); + base.OnException(context); + } + } +} diff --git a/COMCMS.Web/Controllers/api/APIBaseController.cs b/COMCMS.Web/Controllers/api/APIBaseController.cs index 0a1dd58..bcb0d65 100644 --- a/COMCMS.Web/Controllers/api/APIBaseController.cs +++ b/COMCMS.Web/Controllers/api/APIBaseController.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using COMCMS.Common; +using COMCMS.Web.Common; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -10,6 +11,7 @@ namespace COMCMS.Web.Controllers.api { [Produces("application/json")] [Route("api/[controller]/[action]")] + [WebAPIHandleError] public class APIBaseController : Controller { #region 通用信息 diff --git a/COMCMS.Web/Controllers/api/IndexController.cs b/COMCMS.Web/Controllers/api/IndexController.cs index cc3b3ed..b690b6c 100644 --- a/COMCMS.Web/Controllers/api/IndexController.cs +++ b/COMCMS.Web/Controllers/api/IndexController.cs @@ -47,5 +47,15 @@ namespace COMCMS.Web.Controllers.api } } #endregion + + #region 测试出错 + [HttpGet] + public object GetTest() + { + int a = 1,b=0; + var c = a / b; + return reJson; + } + #endregion } }