》》 自定义异常处理特性
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Filters;
namespace WebApplication11
{
/// <summary>
/// 异常处理特性
/// </summary>
public class CustomExceptionAttribute:ExceptionFilterAttribute
{
/// <summary>
/// 方法会在出现异常时触发
/// </summary>
/// <param name="actionExecutedContext"></param>
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
Console.WriteLine($"{ actionExecutedContext.Request.RequestUri.AbsoluteUri}:{actionExecutedContext.Exception.Message}");
//把当前请求的返回指定一下
actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(
HttpStatusCode.OK,
new
{
Result=false,
Msg="请联系管理员"
});
//base.OnException(actionExecutedContext);
}
}
}
》》上面的异常处理有局限性,只有在控制器实例化后,方法执行完之前,出现的异常才能被捕获。所以在控制器中异常是捕获不到的
》》》要捕获全部异常 要用 ExceptionHandler 或者 IExceptionHandler
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.ExceptionHandling;
using System.Web.Http.Results;
namespace WebApplication11
{
public class GlobalExceptionHandler:ExceptionHandler
{
/// <summary>
/// 判断是不是要异常处理
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override bool ShouldHandle(ExceptionHandlerContext context)
{
return context.Request.RequestUri.AbsoluteUri.Contains("api") && base.ShouldHandle(context);
}
/// <summary>
/// 异常处理
/// </summary>
/// <param name="context"></param>
public override void Handle(ExceptionHandlerContext context)
{
context.Result = new ResponseMessageResult(context.Request.CreateResponse(
HttpStatusCode.OK,
new {
Result=false,
Msg="请联系管理员"
}
));
}
}
}
》》ActionFilterAttribute 在Action执行前 触发OnActionExecuting 执行后 OnActionExecuted
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace WebApplication11
{
public class CustomActionFilteAttribute:ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
}
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
//在这里可以解决跨越问题
base.OnActionExecuted(actionExecutedContext);
}
}
}