public string Resolve(ApiInterface source, object destination, string destMember, ResolutionContext context)
        {
            if (!source.IsUseEnvelop)
            {
                try
                {
                    var result = JToken.Parse(source.ResponseResult);
                    return(JsonConvert.SerializeObject(result, Formatting.Indented));
                }
                catch (System.Exception)
                {
                    return("Json内容格式不正确, 通过编辑修复之后再查看");
                }
            }

            var envelop = new EnvelopMessage <object>()
            {
                Code            = 200,
                Tid             = GuidGenerator.GenerateDigitalUUID(),
                FriendlyMessage = "返回成功",
                ErrorMessage    = string.Empty
            };

            try
            {
                envelop.Data = JToken.Parse(source.ResponseResult);
            }
            catch (System.Exception)
            {
                envelop.Data = "Json内容格式不正确, 通过编辑修复之后再查看";
            }
            return(JsonConvert.SerializeObject(envelop, Formatting.Indented));
        }
Exemplo n.º 2
0
        public async Task Invoke(HttpContext context)
        {
            if (!context.Request.Path.HasValue || !context.Request.Path.Value.Contains("/api/", StringComparison.OrdinalIgnoreCase))
            {
                await Next(context);

                return;
            }

            var requestPath = context.Request.Path.Value;
            var pathArray   = requestPath.Trim('/').Split('/');
            var category    = pathArray[0];
            var apiSection  = pathArray[1];
            var realApiPath = requestPath.Substring(category.Length + 1);

            if (!apiSection.Equals("api", StringComparison.OrdinalIgnoreCase))
            {
                await Next(context);

                return;
            }

            var apiInterfaceRepository = context.RequestServices.GetService <MockServerNoSqlRepository <ApiInterface> >();
            var entity = await apiInterfaceRepository.SearchOneAsync(Builders <ApiInterface> .Filter.Where(x => x.Category == category && x.RequestPath == realApiPath));

            if (entity != null)
            {
                if (entity.IsUseEnvelop)
                {
                    var envelop = new EnvelopMessage <object>()
                    {
                        Code            = 200,
                        Tid             = GuidGenerator.GenerateDigitalUUID(),
                        FriendlyMessage = "返回成功",
                        ErrorMessage    = string.Empty
                    };
                    envelop.Data = JToken.Parse(entity.ResponseResult);
                    await HandleStatus(context, envelop);
                }
                else
                {
                    var data = JToken.Parse(entity.ResponseResult);
                    await HandleStatus(context, data);
                }
            }
            else
            {
                await InterfaceNotFound(context);
            }
        }
        public string Resolve(object source, object destination, string sourceMember, string destMember, ResolutionContext context)
        {
            var envelop = new EnvelopMessage <object>()
            {
                Code            = 200,
                Tid             = GuidGenerator.GenerateDigitalUUID(),
                FriendlyMessage = "返回成功",
                ErrorMessage    = string.Empty
            };

            try
            {
                envelop.Data = JToken.Parse(sourceMember);
            }
            catch (System.Exception)
            {
                envelop.Data = "Json内容格式不正确, 通过编辑修复之后再查看";
            }
            return(JsonConvert.SerializeObject(envelop, Formatting.Indented));
        }
        public override void OnActionExecuted(ActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext.Exception != null)    //如果有Exception发生,直接跳过处理
            {
                return;
            }

            if (!actionExecutedContext.HttpContext.Request.IsApiRequest())
            {
                return;
            }

            if (actionExecutedContext.Result is JsonResult jsonResultContent)
            {
                var envelopMessage = new EnvelopMessage <object>(jsonResultContent.Value);
                actionExecutedContext.Result = new OkObjectResult(envelopMessage);
            }
            else if (actionExecutedContext.Result is ObjectResult content)
            {
                if (content.Value is JsonDocument)
                {
                    var jsonDocument   = content.Value as JsonDocument;
                    var envelopMessage = new EnvelopMessage <JsonElement>(jsonDocument.RootElement);
                    actionExecutedContext.Result = new OkObjectResult(envelopMessage);
                }
                else
                {
                    var envelopMessage = new EnvelopMessage <object>(content.Value);
                    actionExecutedContext.Result = new OkObjectResult(envelopMessage);
                }
            }
            else if (actionExecutedContext.Result is EmptyResult)
            {
                var envelopMessage = new EnvelopMessage((int)ApiStatusCode.Success);
                actionExecutedContext.Result = new OkObjectResult(envelopMessage);
            }
        }
Exemplo n.º 5
0
        //https://weblog.west-wind.com/posts/2016/oct/16/error-handling-and-exceptionfilter-dependency-injection-for-aspnet-core-apis
        public override void OnException(ExceptionContext context)
        {
            var logger         = context.HttpContext.RequestServices.GetService <ILogger <ExceptionHandlerFilter> >();
            var requestSession = context.HttpContext.RequestServices.GetRequiredService <IRequestSession>();

            if (!requestSession.IsApiRequest)
            {
                return;
            }

            context.HttpContext.Response.StatusCode = 200;
            EnvelopMessage messageEnvelop = null;

            if (context.Exception is OperationCanceledException)
            {
                //logger.LogError(context.Exception.FullMessage());
                messageEnvelop           = new EnvelopMessage((int)ApiStatusCode.RequestCancelled);
                context.ExceptionHandled = true;
            }
            //else if (context.Exception is ApiAuthenticationException)
            //{
            //    //logger.LogError(context.Exception.FullMessage());
            //    var ex = context.Exception as ApiAuthenticationException;
            //    messageEnvelop = new EnvelopMessage(ex.Code, ex.Message, ex.FriendlyMessage);
            //}
            else if (context.Exception is ModelValidateException)
            {
                //logger.LogError(context.Exception.FullMessage());
                var modelValidationException = (ModelValidateException)context.Exception;
                //只拿到有ErrorMessage
                var allInvalidItems = modelValidationException.ValidateMessage.Where(x => x.Value.ErrorMessage.IsNotNullOrWhitespace()).Select(x => x.Value.ErrorMessage);
                var errorMessage    = modelValidationException.ValidateMessage.Select(x => new KeyValuePair <string, string>(x.Key, x.Value.ErrorMessage.IsNullOrWhitespace() ? x.Value.Exception.FullMessage() : x.Value.ErrorMessage));

                messageEnvelop = new EnvelopMessage(modelValidationException.Code,
                                                    debugMessage: errorMessage.Any() ? string.Join("|", errorMessage.Select(x => $"{x.Key}:{x.Value}")) : null,
                                                    hintMessage: allInvalidItems.Any() ? string.Join(",", allInvalidItems) : null);
            }
            else if (context.Exception is ApiException)
            {
                //logger.LogError(context.Exception.FullMessage());
                // handle explicit 'known' API errors
                var ex = context.Exception as ApiException;
                messageEnvelop = new EnvelopMessage(ex.Code, ex.HintMessage, ex.Message);
            }
            else if (context.Exception is DbException)
            {
                //logger.LogError(context.Exception.FullMessage());
                var ex = context.Exception as DbException;
                messageEnvelop = new EnvelopMessage((int)ApiStatusCode.DatabaseOperationFail,
                                                    debugMessage: $@"数据库访问异常
{ex.FullMessage()}
{ex.FullStacktrace()}
{ex.ToString()}");
            }
            else
            {
                logger.LogError($"Tid:{requestSession.Tid} ErrorMessage:{context.Exception.FullMessage()}, ExceptionType:{context.Exception.GetType().FullName},StackTrace:{context.Exception.FullStacktrace()}");
                messageEnvelop = new EnvelopMessage((int)ApiStatusCode.GeneralError, context.Exception.FullMessage(), "服务器处理异常");
            }

            messageEnvelop.Tid = requestSession.Tid;

            // always return a JSON result
            context.Result           = new JsonResult(messageEnvelop);
            context.ExceptionHandled = true;
        }