/// <summary> /// Не успешный ответ с указанием ошибки и кода ответа /// </summary> /// <param name="error">ошибка</param> /// <param name="statusCode">код ответа</param> protected HttpResponseMessage Failure(string error, HttpStatusCode statusCode = HttpStatusCode.BadRequest) { var result = ResponseModel.Failure(error); var response = Request.CreateResponse(HttpStatusCode.BadRequest); response.Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.UTF8, "application/json"); return(response); }
public override void OnException(HttpActionExecutedContext actionExecutedContext) { var exc = actionExecutedContext.Exception; if (exc is ValidationException) { var result = ResponseModel.Failure(exc.Message); actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.BadRequest); actionExecutedContext.Response.Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.UTF8, "application/json"); } else { var result = ResponseModel.Failure(exc.Message); actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.InternalServerError); actionExecutedContext.Response.Content = new StringContent(JsonConvert.SerializeObject(result), Encoding.UTF8, "application/json"); } base.OnException(actionExecutedContext); }
/// <summary> /// 无效的验证处理, 可重写 /// </summary> /// <param name="errorMessage">错误消息描述</param> /// <param name="context">Action 执行时的上下文</param> public virtual void InvalidValidate(string errorMessage, ActionExecutingContext context) { context.Result = new OkObjectResult(ResponseModel.Failure("4401", errorMessage)); }
/// <summary> /// 处理异常 /// </summary> public virtual void ExceptionHandle(ExceptionContext context) { context.Result = new OkObjectResult( ResponseModel.Failure("4001", "服务器错误")); }