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 = 0, 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>.Error(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 WebApiExceptionFilterAttribute());​


4、HomeApiController,创建一个测试

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