private static void OnError(ActionExecutingContext?context, ErrorCode error)
 {
     if (context != null)
     {
         context.Result = new BadRequestObjectResult(error);
     }
 }
Пример #2
0
        public static Exception WarpException(Exception ex, ActionExecutingContext?context = null)
        {
            var bodyFe = ex as FaultException;

            //normally Exception
            if (bodyFe == null && !(ex is OperationCanceledException))
            {
                var gt = typeof(FaultException <>).MakeGenericType(ex.GetType());
                var fe = (FaultException)Activator.CreateInstance(gt, ex) !;
                if (context != null)
                {
                    fe.AppendMethodInfo(context.ActionInfo, context.Args);
                }
                return(fe);
            }

            //FaultException
            if (bodyFe != null)
            {
                if (context != null)
                {
                    bodyFe.AppendMethodInfo(context.ActionInfo, context.Args);
                }
                return(bodyFe);
            }

            //OperationCanceledException
            return(ex);
        }
Пример #3
0
        public override void OnActionExecuting(ActionExecutingContext?context)
        {
            base.OnActionExecuting(context);

            Validator.CurrentAccountId = Service.CurrentAccountId;
            Validator.ModelState       = ModelState;
            Validator.Alerts           = Alerts;
        }
Пример #4
0
        public async Task HandleRequestAsync()
        {
            ActionExecutingContext?context = null;

            try
            {
                //get context
                context = await GetContext();

                //set Accessor
                _actionExecutingContextAccessor.Context = context;

                //middleware Invoke
                var ret = await _middlewareBuilder.InvokeAsync(context);

                //if Post, do not need send back to client.
                if (context.ContractMethod.IsMQPost)
                {
                    return;
                }

                var hasStream = ret.TryGetStream(out var retStream, out var retStreamName);

                //send result
                var sendStreamNext = await _convert.SendResultAsync(new CustomResult(ret, hasStream, retStream.GetLength()), retStream, retStreamName, context);

                if (!sendStreamNext)
                {
                    return;
                }

                //send stream
                await SendStreamAsync(context, hasStream, retStream);

                context.OnSendResultStreamFinished();
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, "HandleRequestAsync");

                //if Post, do not need send back to client.
                if (context != null && context.ContractMethod.IsMQPost)
                {
                    return;
                }

                //send fault
                try
                {
                    await _convert.SendFaultAsync(e, context);
                }
                catch (Exception e2)
                {
                    _logger.LogWarning(e2, "HandleRequestAsync SendFaultAsync");
                }
            }
        }
Пример #5
0
        /// <inheritdoc />
        public void OnActionExecuting(ActionExecutingContext?context)
        {
            if (context == default)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (context.ModelState.IsValid)
            {
                return;
            }

            context.Result = new BadRequestObjectResult(context.ModelState);
        }
Пример #6
0
 private void HandleKnownExceptions(Exception error, ActionExecutingContext?actionContext, string errorContext)
 {
     using (logger.BeginKeyValueScope("user", User?.Identity?.Name))
         using (logger.BeginKeyValueScope("action", actionContext?.ActionDescriptor?.DisplayName))
             using (logger.BeginKeyValueScope("errorContext", errorContext))
             {
                 if (error is UnauthorizedAccessException)
                 {
                     logger.LogWarning(error.Message);
                 }
                 else if (error is RavenException ravenEx &&
                          ravenEx.Message.Contains("The server returned an invalid or unrecognized response", StringComparison.InvariantCultureIgnoreCase))
                 {
                     logger.LogError(ravenEx.Message);
                 }
Пример #7
0
 public Task SendFaultAsync(Exception body, ActionExecutingContext?context)
 {
     try
     {
         var warpEx = Helper.WarpException(body, context);
         var reply  = Reply.FromFault(warpEx);
         return(SendAsync(reply));
     }
     catch (Exception e)
     {
         _logger.LogWarning(e, "SendFaultAsync error");
         var se  = new SerializationException($"{e.Message}");
         var fse = new FaultException <SerializationException>(se);
         return(SendAsync(Reply.FromFault(fse)));
     }
 }
        /// <inheritdoc />
        public override void OnActionExecuting(ActionExecutingContext?context)
        {
            if (context is null)
            {
                return;
            }

            foreach (var(aKey, aValue) in context.ActionArguments)
            {
                if (aValue is null)
                {
                    continue;
                }

                var type = aValue.GetType();
                if (type == typeof(string))
                {
                    context.ActionArguments[aKey] = aValue.ToString().ApplyCorrectYeKe();
                }
                else
                {
                    var stringProperties = aValue.GetType()
                                           .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                                           .Where(x =>
                                                  x.CanRead &&
                                                  x.CanWrite &&
                                                  x.PropertyType == typeof(string) &&
                                                  x.GetGetMethod(true)?.IsPublic == true &&
                                                  x.GetSetMethod(true)?.IsPublic == true);

                    foreach (var propertyInfo in stringProperties)
                    {
                        var value = propertyInfo.GetValue(aValue);
                        if (value is null)
                        {
                            continue;
                        }

                        propertyInfo.SetValue(aValue, value.ToString().ApplyCorrectYeKe());
                    }
                }
            }
        }
Пример #9
0
        public Task SendFaultAsync(Exception body, ActionExecutingContext?context)
        {
            if (body is HttpNotMatchedException ||
                body is MethodNotFoundException)
            {
                NotMatched = true;
                if (_ignoreWhenNotMatched)
                {
                    return(Task.CompletedTask);
                }
            }

            // UnWarp FaultException
            body = NetRpc.Helper.UnWarpException(body);

            // Cancel
            if (body is OperationCanceledException)
            {
                return(_connection.SendAsync(Result.FromFaultException(new FaultExceptionJsonObj(), ClientConstValue.CancelStatusCode)));
            }

            // ResponseTextException
            if (body is ResponseTextException textEx)
            {
                return(_connection.SendAsync(Result.FromPainText(textEx.Text, textEx.StatusCode)));
            }

            // customs Exception
            // ReSharper disable once UseNullPropagation
            if (context != null)
            {
                var t = context.ContractMethod.FaultExceptionAttributes.FirstOrDefault(i => body.GetType() == i.DetailType);
                if (t != null)
                {
                    return(_connection.SendAsync(Result.FromFaultException(
                                                     new FaultExceptionJsonObj(t.ErrorCode, t.Description ?? body.Message), t.StatusCode)));
                }
            }

            // default Exception
            return(_connection.SendAsync(Result.FromFaultException(new FaultExceptionJsonObj(null, body.Message), ClientConstValue.DefaultExceptionStatusCode)));
        }
        private static void Run(ActionExecutingContext?actionExecutingContext, ActionExecutedContext?actionExecutedContext)
        {
            var isModelValid = Options.IsValidationRunOnActionExecuting
                ? actionExecutingContext?.ModelState.IsValid
                : actionExecutedContext?.ModelState.IsValid;

            if (!isModelValid.HasValue || !isModelValid.Value)
            {
                var modelStateDictionary = Options.IsValidationRunOnActionExecuting
                    ? actionExecutingContext?.ModelState
                    : actionExecutedContext?.ModelState;

                var badRequestResult = new BadRequestObjectResult(modelStateDictionary)
                {
                    StatusCode = (int)Options.ResultingStatusCode
                };

                if (Options.IsValidationRunOnActionExecuting)
                {
                    if (actionExecutingContext != null)
                    {
                        actionExecutingContext.Result = badRequestResult;
                    }
                }
                else
                {
                    if (actionExecutedContext != null)
                    {
                        actionExecutedContext.Result = badRequestResult;
                    }
                }

                Options.OnModelStateInvalid?.Invoke(actionExecutingContext, actionExecutedContext);
            }
            else
            {
                Options.OnModelStateValid?.Invoke(actionExecutingContext, actionExecutedContext);
            }
        }
Пример #11
0
        public override void OnActionExecuting(ActionExecutingContext?context)
        {
            base.OnActionExecuting(context);

            Service.CurrentAccountId = CurrentAccountId;
        }
Пример #12
0
        public override void OnActionExecuting(ActionExecutingContext?context)
        {
            Authorization = HttpContext.RequestServices.GetService <IAuthorization>();

            CurrentAccountId = User.Id() ?? 0;
        }