示例#1
0
        public void WrapperSuccess_MoreCustomerModel()
        {
            var originalData = "dududu";

            CustomWrapperModel customWrapperModel = new CustomWrapperModel();

            customWrapperModel.AddProperty("Name", s => "Name");
            customWrapperModel.AddProperty("Person", s => "Person");
            customWrapperModel.AddProperty("Old", s => "1");

            CustomWrapperModel customWrapperModel2 = new CustomWrapperModel();

            customWrapperModel2.AddProperty("DiDiDi", s => "DiDiDi");

            var costomConfigs = new Dictionary <Range, CustomWrapperModel>();

            costomConfigs.Add(200..201, customWrapperModel);
            costomConfigs.Add(300..401, customWrapperModel2);

            DataWrapperOptions options = new DataWrapperOptions()
            {
                UseCustomModel    = true,
                CustomModelConfig = costomConfigs
            };
            DataWrapperContext context = new DataWrapperContext(new ObjectResult(originalData), CreateFakeHttpContext("Get", 200), options);
            var result = _dataWrapperExecutor.WrapSuccesfullysResult(originalData, context);

            Assert.NotNull(result.GetType().GetProperty("Name").Name);

            DataWrapperContext context2 = new DataWrapperContext(new ObjectResult(originalData), CreateFakeHttpContext("Get", 300), options);
            var result2 = _dataWrapperExecutor.WrapSuccesfullysResult(originalData, context2);

            Assert.NotNull(result2.GetType().GetProperty("DiDiDi").Name);
        }
        public Task OnExceptionAsync(ExceptionContext context)
        {
            if (context.ExceptionHandled)
            {
                return(Task.CompletedTask);
            }

            //httpContext status code is always be 0.

            var wrapContext = new DataWrapperContext(context.Result,
                                                     context.HttpContext,
                                                     _options,
                                                     context.ActionDescriptor);

            var wrappedData = _wrapperExecutor.WrapFailedResult(context.Result, context.Exception, wrapContext);

            if (!(wrappedData is ApiError))
            {
                context.ExceptionHandled = true;
                context.Result           = new ObjectResult(wrappedData);
            }

            //exceptionContext.Result != null || exceptionContext.Exception == null || exceptionContext.ExceptionHandled
            //Therefore, the exceptionContext.Result is not assigned here and is handled by middleware

            return(Task.CompletedTask);
        }
示例#3
0
        public void WrapperSuccess_OneCustomerModel_InRange()
        {
            var originalData = "dududu";

            CustomWrapperModel customWrapperModel = new CustomWrapperModel();

            customWrapperModel.AddProperty("Name", s => "Name");
            customWrapperModel.AddProperty("Person", s => "Person");
            customWrapperModel.AddProperty("Old", s => "1");

            var costomConfigs = new Dictionary <Range, CustomWrapperModel>();

            costomConfigs.Add(200..300, customWrapperModel);

            DataWrapperOptions options = new DataWrapperOptions()
            {
                UseCustomModel    = true,
                CustomModelConfig = costomConfigs
            };
            DataWrapperContext context = new DataWrapperContext(new ObjectResult(originalData), CreateFakeHttpContext("Get", 200), options);
            var result = _dataWrapperExecutor.WrapSuccesfullysResult(originalData, context);

            Assert.NotNull(result);
            Assert.IsAssignableFrom <IResultDataWrapper>(result);
        }
示例#4
0
        public void WrapperSuccess_NormalData_ShouldReturnApiResponse(object originalData)
        {
            DataWrapperOptions options = new DataWrapperOptions();
            DataWrapperContext context = new DataWrapperContext(new ObjectResult(originalData), CreateFakeHttpContext("Get", 200), options);
            var result = _dataWrapperExecutor.WrapSuccesfullysResult(originalData, context);

            Assert.NotNull(result);
            Assert.IsType <ApiResponse>(result);
        }
示例#5
0
        public void WrapperSuccess_NullOptions()
        {
            var originalData = new ObjectResult(123);

            DataWrapperContext optionsNullContext = new DataWrapperContext(new ObjectResult(originalData), CreateFakeHttpContext("Get", 200), null);

            Assert.Throws <ArgumentNullException>(() => _dataWrapperExecutor.WrapSuccesfullysResult(originalData, optionsNullContext));

            DataWrapperContext httpContextNullContext = new DataWrapperContext(new ObjectResult(originalData), null, new DataWrapperOptions());

            Assert.Throws <ArgumentNullException>(() => _dataWrapperExecutor.WrapSuccesfullysResult(originalData, httpContextNullContext));
        }
示例#6
0
        public void WrapperSuccess_OriginalIsProblemDetail_WrapProblemDetailsIsFalse()
        {
            DataWrapperOptions options = new DataWrapperOptions();

            var originalProblemDetail = new BadRequestObjectResult(new ProblemDetails()
            {
                Title = "This is ProblemDetail"
            });
            DataWrapperContext context = new DataWrapperContext(originalProblemDetail, CreateFakeHttpContext("Get", 400), options);
            var result = _dataWrapperExecutor.WrapSuccesfullysResult(originalProblemDetail.Value, context);

            Assert.NotNull(result);
            Assert.Same(originalProblemDetail.Value, result);
        }
示例#7
0
        public void WrapperSuccess_OriginalIsCustomerWrapperData()
        {
            var originalData = new TestResultDataWrapper()
            {
                CompanyName = "MiCake"
            };

            DataWrapperOptions options = new DataWrapperOptions();
            DataWrapperContext context = new DataWrapperContext(new ObjectResult(originalData), CreateFakeHttpContext("Get", 200), options);
            var result = _dataWrapperExecutor.WrapSuccesfullysResult(originalData, context);

            Assert.NotNull(result);
            Assert.Same(originalData, result);
        }
示例#8
0
        public void WrapperSuccess_CustomerModel_NullConfig()
        {
            var originalData = "dududu";

            DataWrapperOptions options = new DataWrapperOptions()
            {
                UseCustomModel    = true,
                CustomModelConfig = null
            };
            DataWrapperContext context = new DataWrapperContext(new ObjectResult(originalData), CreateFakeHttpContext("Get", 200), options);
            var result = _dataWrapperExecutor.WrapSuccesfullysResult(originalData, context);

            Assert.Same(originalData, result);
        }
示例#9
0
        private object AssignValueToCustomType(CustomModelWithType customModelInfo, DataWrapperContext wrapperContext)
        {
            if (customModelInfo == null)
            {
                return(null);
            }

            var modelInstance = Activator.CreateInstance(customModelInfo.EmitType);

            foreach (var customerProperty in customModelInfo.ModelConfig.GetAllConfigProperties())
            {
                var propertyValue = customerProperty.Value(wrapperContext);
                customModelInfo.EmitType.GetProperty(customerProperty.Key)?.SetValue(modelInstance, propertyValue);
            }
            return(modelInstance);
        }
示例#10
0
        public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
        {
            if (context.Result is ObjectResult objectResult)
            {
                var statusCode = objectResult.StatusCode ?? context.HttpContext.Response.StatusCode;

                if (!_options.NoWrapStatusCode.Any(s => s == statusCode))
                {
                    var wrappContext = new DataWrapperContext(context.Result,
                                                              context.HttpContext,
                                                              _options,
                                                              context.ActionDescriptor);

                    var wrappedData = _wrapperExecutor.WrapSuccesfullysResult(objectResult.Value, wrappContext);
                    objectResult.Value        = wrappedData;
                    objectResult.DeclaredType = wrappedData.GetType();
                }
            }

            await next();
        }
示例#11
0
        /// <summary>
        /// Create customModel instance,and given value by config.
        /// </summary>
        /// <param name="wrapperContext"><see cref="DataWrapperContext"/></param>
        /// <returns>customModel instance.</returns>
        protected virtual object CreateCustomModel(DataWrapperContext wrapperContext)
        {
            var currentHttpCode = wrapperContext.HttpContext.Response.StatusCode;

            if (_cacheCustomerType.TryGetValue(currentHttpCode, out var resultConfigInfo))
            {
                return(AssignValueToCustomType(resultConfigInfo, wrapperContext));
            }

            var customModels = wrapperContext.WrapperOptions.CustomModelConfig;

            CustomWrapperModel optimizationCustomModel = null;

            foreach (var customModel in customModels)
            {
                if (customModel.Key.IsInRange(currentHttpCode))
                {
                    optimizationCustomModel = customModel.Value;
                    break;
                }
            }

            if (optimizationCustomModel == null)
            {
                //If it is not empty, it means that there is no configuration,
                //then when the status code is encountered in the future, the source data will be returned
                _cacheCustomerType.TryAdd(currentHttpCode, null);
                return(null);
            }

            var emitType        = CreateCustomEmitType(optimizationCustomModel);
            var customModelInfo = new CustomModelWithType(optimizationCustomModel, emitType);

            _cacheCustomerType.TryAdd(currentHttpCode, customModelInfo);

            return(AssignValueToCustomType(customModelInfo, wrapperContext));
        }
示例#12
0
        /// <summary>
        /// <inheritdoc/>
        /// </summary>
        public virtual object WrapSuccesfullysResult(object orignalData, DataWrapperContext wrapperContext, bool isSoftException = false)
        {
            CheckValue.NotNull(wrapperContext, nameof(wrapperContext));
            CheckValue.NotNull(wrapperContext.HttpContext, nameof(wrapperContext.HttpContext));
            CheckValue.NotNull(wrapperContext.WrapperOptions, nameof(wrapperContext.WrapperOptions));

            if (orignalData is IResultDataWrapper)
            {
                return(orignalData);
            }

            var options   = wrapperContext.WrapperOptions;
            var statuCode = (wrapperContext.ResultData as ObjectResult)?.StatusCode ?? wrapperContext.HttpContext.Response.StatusCode;

            if (!options.UseCustomModel)
            {
                if (isSoftException)
                {
                    var softlyException = wrapperContext.SoftlyException;

                    return(new ApiResponse(softlyException.Message)
                    {
                        Result = softlyException.Details,
                        ErrorCode = softlyException.Code,
                        IsError = true,
                    });
                }

                if (orignalData is ProblemDetails problemDetails)
                {
                    return(options.WrapProblemDetails ? new ApiResponse(problemDetails.Title)
                    {
                        Result = problemDetails.Detail,
                        StatusCode = statuCode,
                        IsError = true,
                    }
                    : orignalData);
                }

                return(new ApiResponse(ResponseMessage.Success, orignalData)
                {
                    StatusCode = statuCode
                });
            }
            else
            {
                if (options.CustomModelConfig == null || options.CustomModelConfig.Count == 0)
                {
                    return(orignalData);
                }

                //create customer model.
                var customerModel = CreateCustomModel(wrapperContext);
                if (customerModel == null)
                {
                    return(orignalData);
                }

                return(customerModel);
            }
        }
示例#13
0
        /// <summary>
        /// <inheritdoc/>
        /// </summary>
        public virtual object WrapFailedResult(object originalData, Exception exception, DataWrapperContext wrapperContext)
        {
            var httpContext = wrapperContext.HttpContext;
            var options     = wrapperContext.WrapperOptions;

            CheckValue.NotNull(httpContext, nameof(HttpContext));
            CheckValue.NotNull(options, nameof(DataWrapperOptions));

            if (exception is ISoftlyMiCakeException)
            {
                //Given Ok Code for this exception.
                httpContext.Response.StatusCode = StatusCodes.Status200OK;
                //Given this exception to context.
                wrapperContext.SoftlyException = exception as SoftlyMiCakeException;

                return(WrapSuccesfullysResult(originalData ?? exception.Message, wrapperContext, true));
            }

            var      micakeException = exception as MiCakeException;
            ApiError result          = new ApiError(exception.Message,
                                                    originalData,
                                                    micakeException?.Code,
                                                    options.IsDebug ? exception.StackTrace : null);

            return(result);
        }