public override void OnActionExecuting(HttpActionContext actionContext) { if (!actionContext.ModelState.IsValid) { //定义错误列表,一次返回 var errorMessage = new List <string>(); foreach (var error in actionContext.ModelState.Values) { foreach (var theError in error.Errors) { errorMessage.Add(theError.ErrorMessage); } } //构造自定义数据格式 var data = new JsonResultBuilder() .SetCode(JsonResultCode.BadRequest) .SetMessage(string.Join(",", string.Join(",", errorMessage))) .SetEmptyResult().Build(); //返回消息体 actionContext.Response = new HttpResponseMessage() { Content = new StringContent(JsonConvert.SerializeObject(data)), StatusCode = HttpStatusCode.BadRequest }; } }
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) { base.HandleUnauthorizedRequest(actionContext); //构造自定义数据格式 var data = new JsonResultBuilder() .SetCode(JsonResultCode.Forbidden) .SetMessage("无效的token") .SetEmptyResult().Build(); //返回消息体 actionContext.Response = new HttpResponseMessage() { Content = new StringContent(JsonConvert.SerializeObject(data)), StatusCode = HttpStatusCode.Forbidden }; }
public override void OnException(HttpActionExecutedContext actionExecutedContext) { logger.Error(actionExecutedContext.Exception); //构造自定义数据格式 var data = new JsonResultBuilder() .SetCode(JsonResultCode.InteralServerError) .SetMessage("服务器内部处理异常") .SetEmptyResult().Build(); //返回消息体 actionExecutedContext.Response = new HttpResponseMessage() { Content = new StringContent(JsonConvert.SerializeObject(data)), StatusCode = HttpStatusCode.InternalServerError }; }