接口 web api 全局异常过滤器

时间:2020-05-20
本文章向大家介绍接口 web api 全局异常过滤器,主要包括接口 web api 全局异常过滤器使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

原文:https://www.cnblogs.com/mstmdev/p/5471099.html



1、JsonMsg,统一返回消息的格式


/// <summary>
/// 返回消息
/// </summary>
public class JsonMsg<T> where T : class
{
    /// <summary>
    /// 状态码 0:失败 1:成功
    /// </summary>
    public int code { get; set; }

    /// <summary>
    /// 消息
    /// </summary>
    public string msg { get; set; }

    /// <summary>
    /// 内容
    /// </summary>
    public T obj { get; set; }

    /// <summary>
    /// 图标
    /// </summary>
    public int icon { get; set; }


    public static JsonMsg<T> OK(T obj, string msg = "成功")
    {
        return new JsonMsg<T>() { code = 1, msg = msg, obj = obj, icon = 1 };
    }

    public static JsonMsg<T> Error(T obj, string msg = "失败")
    {
        return new JsonMsg<T>() { code = 1, msg = msg, obj = obj, icon = 1 };
    }
}

2、WebApiExceptionFilterAttribute,自定义异常过滤器

public class WebApiExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        base.OnException(actionExecutedContext);


        var obj = JsonMsg<string>.OK(null, actionExecutedContext.Exception.Message);

        var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
        response.Content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
        actionExecutedContext.Response = response;
    }
}

3、Global,在Application_Start方法中,添加如下代码

GlobalConfiguration.Configuration.Filters.Add(new Attr.WebApiExceptionFilterAttribute());

4、HomeApiController,创建一个测试

[AllowAnonymous]
public void testEx()
{
    throw new Exception("测试异常信息");
}

原文地址:https://www.cnblogs.com/guxingy/p/12921966.html