public static IHttpActionResult ErrorHttpActionResult(this ApiController apiController, HttpStatusCode httpStatusCode, string msg, Exception exception = null) { var messageModel = new MessageModel <Exception>(); messageModel.Data = exception; messageModel.Msg = msg; messageModel.Status = httpStatusCode; var errorReponse = messageModel.GetHttpResponseMessage(); throw new HttpResponseException(errorReponse); }
/// <summary> /// 处理未授权的请求 /// </summary> /// <param name="actionContext"></param> protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) { if (actionContext == null) { throw new ArgumentNullException("actionContext"); } var messageModel = new MessageModel <string> { Data = null, }; messageModel.Status = HttpStatusCode.Forbidden; messageModel.Msg = "您无权访问此接口"; var reponse = messageModel.GetHttpResponseMessage(); actionContext.Response = reponse; }
/// <summary> /// 异常处理 /// </summary> /// <param name="actionExecutedContext"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public Task OnExceptionAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken) { var traceWriter = GlobalConfiguration.Configuration.Services.GetTraceWriter(); var wholeLink = (GlobalWholeLink)actionExecutedContext.Request.GetDependencyScope().GetService(typeof(GlobalWholeLink)); // 1.异常日志记录 traceWriter.Error(actionExecutedContext.Request, "The whole link id : " + wholeLink.WholeLinkId.ToString() + Environment.NewLine + "Controller : " + actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerType.FullName + Environment.NewLine + "Action : " + actionExecutedContext.ActionContext.ActionDescriptor.ActionName + Environment.NewLine + "ActionArguments : " + JsonConvert.SerializeObject(actionExecutedContext.ActionContext.ActionArguments), actionExecutedContext.Exception); var isDevelopment = string.Equals(Enviroment, "Development", StringComparison.InvariantCultureIgnoreCase); // 2.返回调用方具体的异常信息 if (actionExecutedContext.Exception is NotImplementedException) { actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented); var messageModel = new MessageModel <Exception> { Data = isDevelopment ? actionExecutedContext.Exception : null, Msg = actionExecutedContext.Exception.Message, Status = HttpStatusCode.NotImplemented, }; actionExecutedContext.Response = messageModel.GetHttpResponseMessage(); //throw new HttpResponseException(reponse); } else if (actionExecutedContext.Exception is TimeoutException) { var messageModel = new MessageModel <Exception> { Data = isDevelopment ? actionExecutedContext.Exception : null, Msg = actionExecutedContext.Exception.Message, Status = HttpStatusCode.RequestTimeout, }; actionExecutedContext.Response = messageModel.GetHttpResponseMessage(); //throw new HttpResponseException(reponse); } else if (actionExecutedContext.Exception is HttpResponseException) { var httpReponse = ((HttpResponseException)actionExecutedContext.Exception).Response; var statusCode = httpReponse.StatusCode; var messageModel = new MessageModel <Exception> { Data = isDevelopment ? actionExecutedContext.Exception : null, Msg = httpReponse.Content.ReadAsStringAsync().Result, Status = statusCode, }; actionExecutedContext.Response = messageModel.GetHttpResponseMessage(); //throw new HttpResponseException(reponse); } else if (actionExecutedContext.Exception is ParamterNotExistException) { var messageModel = new MessageModel <Exception> { Data = isDevelopment ? actionExecutedContext.Exception : null, Status = HttpStatusCode.BadRequest, Msg = actionExecutedContext.Exception.Message }; actionExecutedContext.Response = messageModel.GetHttpResponseMessage(); //throw new HttpResponseException(reponse); } // .....这里可以根据项目需要返回到客户端特定的状态码。如果找不到相应的异常,统一返回服务端错误500 else { var messageModel = new MessageModel <Exception> { Data = isDevelopment ? actionExecutedContext.Exception : null, Msg = actionExecutedContext.Exception.Message, Status = HttpStatusCode.InternalServerError, }; actionExecutedContext.Response = messageModel.GetHttpResponseMessage(); //throw new HttpResponseException(reponse); } return(Task.FromResult(0)); }
/// <summary> /// Action执行前 /// </summary> /// <param name="actionContext"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken) { // 查找不进行模型验证的特性 直接返回 var ignoreModelStateValidAttribute = actionContext.ActionDescriptor.GetCustomAttributes <IgnoreModelStateValidAttribute>(); if (ignoreModelStateValidAttribute != null && ignoreModelStateValidAttribute.Count > 0) { return(Task.FromResult(0)); } var trace = GlobalConfiguration.Configuration.Services.GetTraceWriter(); var wholeLink = (GlobalWholeLink)actionContext.Request.GetDependencyScope().GetService(typeof(GlobalWholeLink)); if (actionContext.ModelState.IsValid) { trace.Info(actionContext.Request, "The whole link id : " + wholeLink.WholeLinkId.ToString() + Environment.NewLine + "Controller : " + actionContext.ControllerContext.ControllerDescriptor.ControllerType.FullName + Environment.NewLine + "Action : " + actionContext.ActionDescriptor.ActionName + Environment.NewLine + "ActionArguments : " + JsonConvert.SerializeObject(actionContext.ActionArguments), "JSON", actionContext.ActionArguments); if (actionContext.ActionArguments != null) { foreach (var argument in actionContext.ActionArguments) { if (argument.Value == null) { var messageModel = new MessageModel <string> { Data = $"参数{argument.Key}是必须的", }; messageModel.Status = HttpStatusCode.BadRequest; messageModel.Msg = "无效的请求"; var reponse = messageModel.GetHttpResponseMessage(); actionContext.Response = reponse; return(Task.FromResult(0)); } } } } else { trace.Warn(actionContext.Request, "The whole link id :" + wholeLink.WholeLinkId.ToString() + Environment.NewLine + "Controller : " + actionContext.ControllerContext.ControllerDescriptor.ControllerType.FullName + Environment.NewLine + "Action : " + actionContext.ActionDescriptor.ActionName + Environment.NewLine + "ActionArguments : " + JsonConvert.SerializeObject(actionContext.ActionArguments) + Environment.NewLine + "ModelState : " + JsonConvert.SerializeObject(actionContext.ModelState), "JSON", actionContext.ActionArguments); var messageModel = new MessageModel <ModelStateDictionary> { Data = actionContext.ModelState, }; messageModel.Status = HttpStatusCode.BadRequest; messageModel.Msg = "无效的请求"; var reponse = messageModel.GetHttpResponseMessage(); actionContext.Response = reponse; } return(Task.FromResult(0)); }
public async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken) { string sign = string.Empty, timestamp = string.Empty, nonce = string.Empty, appKey = string.Empty; if (actionContext.Request.Headers.TryGetValues("sign", out IEnumerable <string> signHeaders)) { sign = signHeaders.First(); } if (actionContext.Request.Headers.TryGetValues("timestamp", out IEnumerable <string> timestampHeaders)) { timestamp = timestampHeaders.First(); } if (actionContext.Request.Headers.TryGetValues("nonce", out IEnumerable <string> nonceHeaders)) { nonce = nonceHeaders.First(); } if (actionContext.Request.Headers.TryGetValues("appkey", out IEnumerable <string> appidHeaders)) { appKey = appidHeaders.First(); } var trace = GlobalConfiguration.Configuration.Services.GetTraceWriter(); var wholeLink = (GlobalWholeLink)actionContext.Request.GetDependencyScope().GetService(typeof(GlobalWholeLink)); trace.Debug(actionContext.Request, "The whole link id : " + wholeLink.WholeLinkId.ToString() + Environment.NewLine + "sign : " + sign + Environment.NewLine + "timestamp : " + timestamp + Environment.NewLine + "nonce : " + nonce, Environment.NewLine + "appkey : " + appKey, "JSON", actionContext.ActionArguments); #region 验证参数的合法性 var messageModel = new MessageModel <string> { Status = HttpStatusCode.BadRequest, Msg = "无效的请求" }; if (string.IsNullOrEmpty(sign) || string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(nonce) || string.IsNullOrEmpty(appKey)) { messageModel.Data = "请求头headers中缺少相关的验证信息"; var reponse = messageModel.GetHttpResponseMessage(); actionContext.Response = reponse; return; } var appService = (IAppInfoService)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IAppInfoService)); var appInfo = (await appService.QueryAsync(q => q.AppId == appKey)).FirstOrDefault(); if (appInfo == null || !appInfo.IsEnable) { messageModel.Data = "请求头headers中的appid不合法"; var reponse = messageModel.GetHttpResponseMessage(); actionContext.Response = reponse; return; } if (long.TryParse(timestamp, out long requestTime)) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区 DateTime checkTime; if (timestamp.Length == 13) //时间戳是自 1970 年 1 月 1 日(00:00:00 GMT)以来的毫秒数 { checkTime = startTime.AddMilliseconds(requestTime); } else // Unix时间戳时间戳是自 1970 年 1 月 1 日(00:00:00 GMT)以来的秒数 { checkTime = startTime.AddSeconds(requestTime); } // 判断时间是不是过期了 if (checkTime.AddSeconds(5 * 60) < DateTime.Now) { messageModel.Data = "请求头headers中的timestamp过期"; var reponse = messageModel.GetHttpResponseMessage(); actionContext.Response = reponse; return; } } else { messageModel.Data = "请求头headers中的timestamp不合法"; var reponse = messageModel.GetHttpResponseMessage(); actionContext.Response = reponse; return; } var computedSign = Md5Helper.GetMD5Hash(appInfo.AppSecret + timestamp + nonce); if (!sign.Equals(computedSign, StringComparison.CurrentCultureIgnoreCase)) { messageModel.Data = "参数可能被篡改,无法处理该请求"; var reponse = messageModel.GetHttpResponseMessage(); actionContext.Response = reponse; return; } #endregion 验证参数的合法性 }