private static void SetAbpActionInfoToHttpContext(HttpContext context, MethodInfo methodInfo) { context.Items["_AbpActionInfo"] = new AbpActionInfoInHttpContext { IsObjectResult = ActionResultHelper.IsObjectResult(methodInfo.ReturnType) }; }
protected virtual void HandleAndWrapException(PageHandlerExecutedContext context, WrapResultAttribute wrapResultAttribute) { if (!ActionResultHelper.IsObjectResult(context.HandlerMethod.MethodInfo.ReturnType)) { return; } var displayUrl = context.HttpContext.Request.GetDisplayUrl(); if (_abpWebCommonModuleConfiguration.WrapResultFilters.HasFilterForWrapOnError(displayUrl, out var wrapOnError)) { context.HttpContext.Response.StatusCode = GetStatusCode(context, wrapOnError); if (!wrapOnError) { return; } HandleError(context); return; } context.HttpContext.Response.StatusCode = GetStatusCode(context, wrapResultAttribute.WrapOnError); if (!wrapResultAttribute.WrapOnError) { return; } HandleError(context); }
protected virtual void HandleAndWrapException(PageHandlerExecutedContext context, WrapResultAttribute wrapResultAttribute) { if (!ActionResultHelper.IsObjectResult(context.HandlerMethod.MethodInfo.ReturnType)) { return; } context.HttpContext.Response.StatusCode = GetStatusCode(context, wrapResultAttribute.WrapOnError); if (!wrapResultAttribute.WrapOnError) { return; } context.Result = new ObjectResult( new AjaxResponse( _errorInfoBuilder.BuildForException(context.Exception), context.Exception is AbpAuthorizationException ) ); EventBus.Trigger(this, new AbpHandledExceptionData(context.Exception)); context.Exception = null; //Handled! }
public async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next) { if (context.HandlerMethod == null || !context.ActionDescriptor.IsPageAction()) { await next(); return; } var methodInfo = context.HandlerMethod.MethodInfo; var unitOfWorkAttr = UnitOfWorkHelper.GetUnitOfWorkAttributeOrNull(methodInfo); context.HttpContext.Items["_AbpActionInfo"] = new AbpActionInfoInHttpContext { IsObjectResult = ActionResultHelper.IsObjectResult(context.HandlerMethod.MethodInfo.ReturnType, typeof(void)) }; if (unitOfWorkAttr?.IsDisabled == true) { await next(); return; } var options = CreateOptions(context, unitOfWorkAttr); var unitOfWorkManager = context.GetRequiredService <IUnitOfWorkManager>(); //Trying to begin a reserved UOW by AbpUnitOfWorkMiddleware if (unitOfWorkManager.TryBeginReserved(UnitOfWork.UnitOfWorkReservationName, options)) { var result = await next(); if (Succeed(result)) { await SaveChangesAsync(context, unitOfWorkManager); } else { await RollbackAsync(context, unitOfWorkManager); } return; } using (var uow = unitOfWorkManager.Begin(options)) { var result = await next(); if (Succeed(result)) { await uow.CompleteAsync(context.HttpContext.RequestAborted); } else { await uow.RollbackAsync(context.HttpContext.RequestAborted); } } }
public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { // Allow Anonymous skips all authorization if (context.Filters.Any(item => item is IAllowAnonymousFilter)) { return; } //TODO: Avoid using try/catch, use conditional checking try { await _authorizationHelper.AuthorizeAsync( context.ActionDescriptor.GetMethodInfo(), context.ActionDescriptor.GetMethodInfo().DeclaringType ); } catch (AbpAuthorizationException ex) { Logger.Warn(ex.ToString(), ex); _eventBus.Trigger(this, new AbpHandledExceptionData(ex)); if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { context.Result = new ObjectResult(new AjaxResponse(_errorInfoBuilder.BuildForException(ex), true)) { StatusCode = context.HttpContext.User.Identity.IsAuthenticated ? (int)System.Net.HttpStatusCode.Forbidden : (int)System.Net.HttpStatusCode.Unauthorized }; } else { context.Result = new ChallengeResult(); } } catch (Exception ex) { Logger.Error(ex.ToString(), ex); _eventBus.Trigger(this, new AbpHandledExceptionData(ex)); if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { context.Result = new ObjectResult(new AjaxResponse(_errorInfoBuilder.BuildForException(ex))) { StatusCode = (int)System.Net.HttpStatusCode.InternalServerError }; } else { //TODO: How to return Error page? context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.InternalServerError); } } }
public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { // Allow Anonymous skips all authorization if (context.Filters.Any(item => item is IAllowAnonymousFilter)) { return; } if (!context.ActionDescriptor.IsControllerAction()) { return; } //TODO: Avoid using try/catch, use conditional checking try { await _authorizationHelper.AuthorizeAsync( context.ActionDescriptor.GetMethodInfo(), context.ActionDescriptor.GetMethodInfo().DeclaringType ); } catch (AuthorizationException ex) { LogUtil.Warn(ex); if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { var isLogin = await _authorizationHelper.CheckLoginAsync(); var errorInfo = ExceptionConvertUtil.Convert(ex); context.Result = new ObjectResult(new AjaxResponse(errorInfo)) { StatusCode = isLogin ? (int)System.Net.HttpStatusCode.Forbidden : (int)System.Net.HttpStatusCode.Unauthorized }; } else { context.Result = new ChallengeResult(); } } catch (Exception ex) { LogUtil.Error(ex); if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { context.Result = new ObjectResult(new OperateResult(ex)) { StatusCode = (int)System.Net.HttpStatusCode.InternalServerError }; } else { context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.InternalServerError); } } }
// 处理并包装异常 private void HandleAndWrapException(ExceptionContext context) { // 判断被调用接口的返回值是否符合标准,不符合则直接返回 if (!ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { return; } // 设置 HTTP 上下文响应所返回的错误代码,由具体异常决定。 context.HttpContext.Response.StatusCode = GetStatusCode(context); //// 重新封装响应返回的具体内容。采用 AjaxResponse 进行封装 //context.Result = new ObjectResult( // new AjaxResponse( // _errorInfoBuilder.BuildForException(context.Exception), // context.Exception is AbpAuthorizationException // ) //); //自定义响应数据格式 var errInfo = _errorInfoBuilder.BuildForException(context.Exception); var sb = new StringBuilder(); if (errInfo.ValidationErrors != null) { foreach (var err in errInfo.ValidationErrors) { sb.AppendLine($"【{string.Join(',', err.Members)}】:{err.Message}"); } } else { sb.Append(context.Exception.Message); } if (context.Exception is UserFriendlyException == false) { errInfo.Code = -1; } ContentResult content = new ContentResult(); content.Content = JsonConvert.SerializeObject(ActionRes.Fail(-1, sb.ToString(), errInfo), new JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }); context.Result = content; // 触发异常处理事件 EventBus.Trigger(this, new AbpHandledExceptionData(context.Exception)); // 处理完成,将异常上下文的内容置为空 context.Exception = null; //Handled! }
public async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next) { if (context.HandlerMethod == null || !context.ActionDescriptor.IsPageAction()) { await next(); return; } var methodInfo = context.HandlerMethod.MethodInfo; var unitOfWorkAttr = UnitOfWorkHelper.GetUnitOfWorkAttributeOrNull(methodInfo); context.HttpContext.Items["_RocketActionInfo"] = new RocketActionInfoInHttpContext { IsObjectResult = ActionResultHelper.IsObjectResult(context.HandlerMethod.MethodInfo.ReturnType) }; if (unitOfWorkAttr?.IsDisabled == true) { await next(); return; } var options = CreateOptions(context, unitOfWorkAttr); //Trying to begin a reserved UOW by RocketUnitOfWorkMiddleware if (_unitOfWorkManager.TryBeginReserved(RocketUnitOfWorkMiddleware.UnitOfWorkReservationName, options)) { var result = await next(); if (!Succeed(result)) { await RollbackAsync(context); } return; } //Begin a new, independent unit of work using (var uow = _unitOfWorkManager.Begin(options)) { var result = await next(); if (Succeed(result)) { await uow.CompleteAsync(context.HttpContext.RequestAborted); } } }
public IActionResult HandleException(ActionContext context, Exception exception) { try { var errorInfo = errorInfoBuilder.BuildInfo(exception); if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { return(exception switch { AuthorizationException _ => CreateFromAuthorizationException(context, errorInfo), ValidationException _ => CreateFromValidationException(errorInfo), _ => CreateFromGenericException(errorInfo), }); }
private void HandlerUnAuthorization(AuthorizationFilterContext context, SecurityException ex) { if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { context.Result = new ObjectResult(new AjaxResponse(_errorInfoBuilder.BuildForException(ex), true)) { StatusCode = context.HttpContext.User.Identity.IsAuthenticated ? (int)System.Net.HttpStatusCode.Forbidden : (int)System.Net.HttpStatusCode.Unauthorized }; } else { context.Result = new ChallengeResult(); } }
// 处理并包装异常 protected virtual void HandleAndWrapException(ExceptionContext context, WrapResultAttribute wrapResultAttribute) { if (!ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { return; } //var displayUrl = context.HttpContext.Request.GetDisplayUrl(); //if (_abpWebCommonModuleConfiguration.WrapResultFilters.HasFilterForWrapOnError(displayUrl, // out var wrapOnError)) //{ // context.HttpContext.Response.StatusCode = GetStatusCode(context, wrapOnError); // if (!wrapOnError) // { // return; // } // HandleError(context); // return; //} //context.HttpContext.Response.StatusCode = GetStatusCode(context, wrapResultAttribute.WrapOnError); //if (!wrapResultAttribute.WrapOnError) //{ // return; //} //HandleError(context); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK; var errorInfo = _errorInfoBuilder.BuildForException(context.Exception); errorInfo.Message = context.Exception.Message; errorInfo.Code = GetStatusCode(context, errorInfo); context.Result = new ObjectResult( new AjaxResponse( errorInfo, context.Exception is AbpAuthorizationException ) ); EventBus.Trigger(this, new AbpHandledExceptionData(context.Exception)); context.Exception = null; //Handled! }
private void ChimaHandleAndWrapException(ExceptionContext context) { if (!ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { return; } context.HttpContext.Response.StatusCode = GetStatusCode(context); context.Result = new ObjectResult( _errorInfoBuilder.BuildForException(context.Exception) ); EventBus.Trigger(this, new AbpHandledExceptionData(context.Exception)); context.Exception = null; //Handled! }
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { //TODO: Configuration to disable validation for controllers..? if (!context.ActionDescriptor.IsControllerAction() || !ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { await next(); return; } using (AbpCrossCuttingConcerns.Applying(context.Controller, AbpCrossCuttingConcerns.Validation)) { _validator.Validate(context.ModelState); await next(); } }
private void HandleAndWrapException(ExceptionContext context) { if (!ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { return; } context.HttpContext.Response.StatusCode = GetStatusCode(context); context.Result = new ObjectResult( new AjaxResponse( _errorInfoBuilder.BuildForException(context.Exception), context.Exception is SecurityException ) ); context.Exception = null; // Handled! }
private bool ShouldHandleException(ExceptionContext context) { if (context.ActionDescriptor.IsControllerAction() && ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { //TODO: Create DontWrap attribute to control wrapping..? return(true); } var accept = context.HttpContext.Request.Headers["Accept"]; if (accept.ToString().Contains("application/json")) //TODO: Optimize { return(true); } return(false); }
protected virtual void HandleAndWrapException(ExceptionContext context) { if (!ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { return; } context.HttpContext.Response.StatusCode = GetStatusCode(context); context.Result = new ObjectResult( new AjaxResponse( _errorInfoBuilder.BuildForException(context.Exception), context.Exception is AbpAuthorizationException ) ); EventBus.Trigger(this, new AbpHandledExceptionData(context.Exception)); context.Exception = null; //Handled! }
protected virtual bool ShouldHandleException(PageHandlerExecutingContext context) { //TODO: Create DontWrap attribute to control wrapping..? if (context.ActionDescriptor.IsPageAction() && ActionResultHelper.IsObjectResult(context.HandlerMethod.MethodInfo.ReturnType, typeof(void))) { return(true); } if (context.HttpContext.Request.CanAccept(MimeTypes.Application.Json)) { return(true); } if (context.HttpContext.Request.IsAjax()) { return(true); } return(false); }
protected virtual void HandleAndWrapException(ExceptionContext context, WrapResultAttribute wrapResultAttribute) { if (!ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { return; } context.HttpContext.Response.StatusCode = GetStatusCode(context, wrapResultAttribute.WrapOnError); if (!wrapResultAttribute.WrapOnError) { return; } context.Result = new ObjectResult( new AjaxResponse( _errorInfoBuilder.BuildForException(context.Exception) ) ); EventBus.Trigger(this, new SharePlatformHandledExceptionData(context.Exception)); context.Exception = null; //Handled! }
public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { // Allow Anonymous skips all authorization if (context.Filters.Any(item => item is IAllowAnonymousFilter)) { return; } if (!context.ActionDescriptor.IsControllerAction()) { return; } var isWebserviceWay = false; if (context.HttpContext.Request.Headers.ContainsKey("requestWay") || context.HttpContext.Request.Headers["requestWay"].ToString() != "webapi") { isWebserviceWay = true; } //TODO: Avoid using try/catch, use conditional checking try { await _authorizationHelper.AuthorizeAsync( context.ActionDescriptor.GetMethodInfo(), context.ActionDescriptor.GetMethodInfo().DeclaringType ); } catch (AbpAuthorizationException ex) { Logger.Warn(ex.ToString(), ex); _eventBus.Trigger(this, new AbpHandledExceptionData(ex)); if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { if (isWebserviceWay) { context.Result = new ObjectResult(new ResultMessage <object>(ResultCode.Auth_Error, "authorization failure")); } else { context.Result = new ObjectResult(new AjaxResponse(_errorInfoBuilder.BuildForException(ex), true)) { StatusCode = context.HttpContext.User.Identity.IsAuthenticated? (int)System.Net.HttpStatusCode.Forbidden:(int)System.Net.HttpStatusCode.Unauthorized }; } } else { if (isWebserviceWay) { context.Result = new ObjectResult(new ResultMessage <object>(ResultCode.Auth_Error, "authorization failure")); } else { context.Result = new ChallengeResult(); } } } catch (Exception ex) { Logger.Error(ex.ToString(), ex); _eventBus.Trigger(this, new AbpHandledExceptionData(ex)); if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { if (isWebserviceWay) { context.Result = new ObjectResult(new ResultMessage <object>(ResultCode.SytemError, "Unknown exception")); } else { context.Result = new ObjectResult(new AjaxResponse(_errorInfoBuilder.BuildForException(ex))) { StatusCode = (int)System.Net.HttpStatusCode.InternalServerError }; } } else { if (isWebserviceWay) { context.Result = new ObjectResult(new ResultMessage <object>(ResultCode.SytemError, "Unknown exception")); } else { //TODO: How to return Error page? context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.InternalServerError); } } } }
public virtual async Task OnAuthorizationAsync(AuthorizationFilterContext context) { var endpoint = context?.HttpContext?.GetEndpoint(); // 如果注入了 IAllowAnonymous 接口则允许所有匿名用户的请求 // Allow Anonymous skips all authorization if (endpoint?.Metadata.GetMetadata <IAllowAnonymous>() != null) { return; } // 如果不是一个控制器方法则直接返回 if (!context.ActionDescriptor.IsControllerAction()) { return; } //TODO: Avoid using try/catch, use conditional checking // 开始使用 IAuthorizationHelper 对象来进行权限校验 try { await _authorizationHelper.AuthorizeAsync( context.ActionDescriptor.GetMethodInfo(), context.ActionDescriptor.GetMethodInfo().DeclaringType ); } // 如果是未授权异常的处理逻辑 catch (AbpAuthorizationException ex) { // 记录日志 Logger.Warn(ex.ToString(), ex); // 触发异常事件 await _eventBus.TriggerAsync(this, new AbpHandledExceptionData(ex)); // 如果接口的返回类型为 ObjectResult,则采用 AjaxResponse 对象进行封装信息 if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { //context.Result = new ObjectResult(new AjaxResponse(_errorInfoBuilder.BuildForException(ex), true)) //{ // StatusCode = context.HttpContext.User.Identity.IsAuthenticated // ? (int)System.Net.HttpStatusCode.Forbidden // : (int)System.Net.HttpStatusCode.Unauthorized //}; //获取错误信息 var errorInfo = _errorInfoBuilder.BuildForException(ex); //code设置状态码数据 errorInfo.Code = (context.HttpContext.User.Identity.IsAuthenticated ? (int)System.Net.HttpStatusCode.Forbidden : (int)System.Net.HttpStatusCode.Unauthorized); //返回结果 context.Result = new ObjectResult(new AjaxResponse(errorInfo, unAuthorizedRequest: true)) { //默认状态 StatusCode = (int)System.Net.HttpStatusCode.OK }; } else { context.Result = new ChallengeResult(); } } // 其他异常则显示为服务器内部异常 catch (Exception ex) { Logger.Error(ex.ToString(), ex); await _eventBus.TriggerAsync(this, new AbpHandledExceptionData(ex)); if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { //context.Result = new ObjectResult(new AjaxResponse(_errorInfoBuilder.BuildForException(ex))) //{ // StatusCode = (int)System.Net.HttpStatusCode.InternalServerError //}; //获取错误信息 var errorInfo = _errorInfoBuilder.BuildForException(ex); errorInfo.Details = ex.Message; errorInfo.Code = (int)System.Net.HttpStatusCode.InternalServerError; context.Result = new ObjectResult(new AjaxResponse(errorInfo)) { StatusCode = (int)System.Net.HttpStatusCode.OK }; } else { //TODO: How to return Error page? context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.InternalServerError); } } }
public virtual async Task OnAuthorizationAsync(AuthorizationFilterContext context) { var endpoint = context?.HttpContext?.GetEndpoint(); // Allow Anonymous skips all authorization if (endpoint?.Metadata.GetMetadata <IAllowAnonymous>() != null) { return; } if (!context.ActionDescriptor.IsControllerAction()) { return; } //TODO: Avoid using try/catch, use conditional checking try { await _authorizationHelper.AuthorizeAsync( context.ActionDescriptor.GetMethodInfo(), context.ActionDescriptor.AsControllerActionDescriptor()?.ControllerTypeInfo.AsType() ); } catch (AbpAuthorizationException ex) { Logger.Warn(ex.ToString(), ex); await _eventBus.TriggerAsync(this, new AbpHandledExceptionData(ex)); if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { context.Result = new ObjectResult(new AjaxResponse(_errorInfoBuilder.BuildForException(ex), true)) { StatusCode = context.HttpContext.User.Identity.IsAuthenticated ? (int)System.Net.HttpStatusCode.Forbidden : (int)System.Net.HttpStatusCode.Unauthorized }; } else { context.Result = new ChallengeResult(); } } catch (Exception ex) { Logger.Error(ex.ToString(), ex); await _eventBus.TriggerAsync(this, new AbpHandledExceptionData(ex)); if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { context.Result = new ObjectResult(new AjaxResponse(_errorInfoBuilder.BuildForException(ex))) { StatusCode = (int)System.Net.HttpStatusCode.InternalServerError }; } else { //TODO: How to return Error page? context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.InternalServerError); } } }
public async Task OnAuthorizationAsync(AuthorizationFilterContext context) { if (context.Filters.Any(item => item is IAllowAnonymousFilter)) { return; } if (!context.ActionDescriptor.IsControllerAction()) { return; } //TODO: Avoid using try/catch, use conditional checking try { await _authorizationHelper.CheckPermissionsAsync( context.ActionDescriptor.GetMethodInfo(), context.ActionDescriptor.GetMethodInfo().DeclaringType); } catch (AncAuthorizationException ex) { _logger.LogWarning(ex.ToString(), ex); //_eventBus.Trigger(this, new AbpHandledExceptionData(ex)); if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { context.Result = new ObjectResult(new Result() { Status = Status.Failure, Message = ex.Message }) { StatusCode = context.HttpContext.User.Identity.IsAuthenticated ? (int)System.Net.HttpStatusCode.Forbidden : (int)System.Net.HttpStatusCode.Unauthorized }; } else { context.Result = new ChallengeResult(); } } catch (Exception ex) { _logger.LogError(ex.ToString(), ex); if (ActionResultHelper.IsObjectResult(context.ActionDescriptor.GetMethodInfo().ReturnType)) { context.Result = new ObjectResult(new { Error = ex, UnAuthorizedRequest = false, Success = false, }) { StatusCode = (int)System.Net.HttpStatusCode.InternalServerError }; } else { //TODO: How to return Error page? context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.InternalServerError); } } }
/// <summary> /// /// </summary> /// <param name="actionDescriptor"></param> /// <returns></returns> public static bool HasObjectResult(this ActionDescriptor actionDescriptor) => ActionResultHelper.IsObjectResult(actionDescriptor.GetReturnType());