/// <summary>
        /// 设置验证失败结果
        /// </summary>
        /// <param name="context">动作方法执行上下文</param>
        /// <param name="modelState">模型验证状态</param>
        /// <param name="actionDescriptor"></param>
        /// <param name="isMvcController"></param>
        private static void SetValidateFailedResult(ActionExecutingContext context, ModelStateDictionary modelState, ControllerActionDescriptor actionDescriptor, bool isMvcController)
        {
            // 解析验证消息
            var(validationResults, validateFaildMessage, _) = ValidatorContext.OutputValidationInfo(modelState);

            // 判断是否跳过规范化结果
            if (isMvcController || UnifyContext.IsSkipUnifyHandler(actionDescriptor.MethodInfo, out var unifyResult))
            {
                // 返回 400 错误
                var result = new BadRequestObjectResult(modelState);

                // 设置返回的响应类型
                result.ContentTypes.Add(MediaTypeNames.Application.Json);
                result.ContentTypes.Add(MediaTypeNames.Application.Xml);

                context.Result = result;
            }
            else
            {
                context.Result = unifyResult.OnValidateFailed(context, modelState, validationResults, validateFaildMessage);
            }

            // 打印验证失败信息
            if (!isMvcController)
            {
                App.PrintToMiniProfiler(MiniProfilerCategory, "Failed", $"Validation Failed:\r\n{validateFaildMessage}", true);
            }
        }
Example #2
0
 static void Main(string[] args)
 {
     using (var db = new UnifyContext())
     {
         var company = db.Set <Company>().First();
     }
 }
Example #3
0
 static void Init()
 {
     using (var db = new UnifyContext())
     {
         db.Database.CreateIfNotExists();
         var Company = new Company("LFG", "LGPMS", "https://www.bing.com", "Test");
         db.Set <Company>().Add(Company);
         //var Company = db.Set<Company>().First();
         var User = new User(Company.Id, "IT", "12345678", "Tim", "123456", "Programming", "15234592255", "*****@*****.**", null);
         db.Set <User>().Add(User);
         //var User = db.Set<User>().First();
         var Role = new Role(Company.Id, "Admin", "Admin", User.Id);
         db.Set <Role>().Add(Role);
         //var Role = db.Set<Role>().First();
         var Function = new FunctionModel("Pms", "Project", "项目", "View", "View", User.Id);
         db.Set <FunctionModel>().Add(Function);
         var RoleUser = new RoleUser(Role.Id, User.Id, User.Id);
         db.Set <RoleUser>().Add(RoleUser);
         var RolePermission = new RolePermission(Role.Id, Function.Id, User.Id);
         db.Set <RolePermission>().Add(RolePermission);
         db.SaveChanges();
         Console.WriteLine("Save successful");
         Console.ReadLine();
     }
 }
Example #4
0
        /// <summary>
        /// 成功返回值
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public IActionResult OnSucceeded(ActionExecutedContext context)
        {
            object data;

            // 处理内容结果
            if (context.Result is ContentResult contentResult)
            {
                data = contentResult.Content;
            }
            // 处理对象结果
            else if (context.Result is ObjectResult objectResult)
            {
                data = objectResult.Value;
            }
            else if (context.Result is EmptyResult)
            {
                data = null;
            }
            else
            {
                return(null);
            }

            return(new JsonResult(new ApiResponse <object>
            {
                Code = context.Result is EmptyResult ? StatusCodes.Status204NoContent : StatusCodes.Status200OK,  // 处理没有返回值情况 204
                Success = true,
                Data = data,
                Msg = null,
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            }));
        }
Example #5
0
        /// <summary>
        /// 设置验证失败结果
        /// </summary>
        /// <param name="context">动作方法执行上下文</param>
        /// <param name="modelState">模型验证状态</param>
        /// <param name="actionDescriptor"></param>
        private static void SetValidateFailedResult(ActionExecutingContext context, ModelStateDictionary modelState, ControllerActionDescriptor actionDescriptor)
        {
            // 将验证错误信息转换成字典并序列化成 Json
            var validationResults = modelState.ToDictionary(u => !JsonSerializerUtility.EnabledPascalPropertyNaming ? u.Key.ToTitlePascal() : u.Key
                                                            , u => modelState[u.Key].Errors.Select(c => c.ErrorMessage));
            var validateFaildMessage = JsonSerializerUtility.Serialize(validationResults);

            // 判断是否跳过规范化结果
            if (UnifyContext.IsSkipUnifyHandler(actionDescriptor.MethodInfo, out var unifyResult))
            {
                // 返回 400 错误
                var result = new BadRequestObjectResult(modelState);

                // 设置返回的响应类型
                result.ContentTypes.Add(MediaTypeNames.Application.Json);
                result.ContentTypes.Add(MediaTypeNames.Application.Xml);

                context.Result = result;
            }
            else
            {
                context.Result = unifyResult.OnValidateFailed(context, modelState, validationResults, validateFaildMessage);
            }

            // 打印验证失败信息
            App.PrintToMiniProfiler(MiniProfilerCategory, "Failed", $"Validation Failed:\r\n{validateFaildMessage}", true);
        }
        /// <summary>
        ///     异常返回值
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public IActionResult OnException(ExceptionContext context)
        {
            // 解析异常信息
            var(ErrorCode, ErrorObject) = UnifyContext.GetExceptionMetadata(context);

            return(new JsonResult(new TData <object>
            {
                Message = ErrorObject.ToString()
            }));
        }
        /// <summary>
        /// 动作方法执行之前操作
        /// </summary>
        /// <param name="context"></param>
        public void OnActionExecuting(ActionExecutingContext context)
        {
            // 获取控制器/方法信息
            var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;

            // 跳过验证类型
            var nonValidationAttributeType = typeof(NonValidationAttribute);
            var method = actionDescriptor.MethodInfo;

            // 如果参数为 0或贴了 [NonValidation] 特性 或所在类型贴了 [NonValidation] 特性,则跳过验证
            if (actionDescriptor.Parameters.Count == 0 ||
                method.IsDefined(nonValidationAttributeType, true) ||
                method.DeclaringType.IsDefined(nonValidationAttributeType, true))
            {
                return;
            }

            // 获取验证状态
            var modelState = context.ModelState;

            // 判断是否验证成功
            if (modelState.IsValid)
            {
                return;
            }

            // 如果其他过滤器已经设置了结果,那么跳过
            if (context.Result != null)
            {
                return;
            }

            // 解析验证消息
            var validationMetadata = ValidatorContext.GetValidationMetadata(modelState);

            // 判断是否跳过规范化结果,如果跳过,返回 400 BadRequestResult
            if (UnifyContext.CheckFailedNonUnify(actionDescriptor.MethodInfo, out var unifyResult))
            {
                context.Result = new BadRequestResult();
            }
            else
            {
                // 判断是否支持 MVC 规范化处理
                if (!UnifyContext.CheckSupportMvcController(context.HttpContext, actionDescriptor, out _))
                {
                    return;
                }

                context.Result = unifyResult.OnValidateFailed(context, validationMetadata);
            }

            // 打印验证失败信息
            App.PrintToMiniProfiler("validation", "Failed", $"Validation Failed:\r\n{validationMetadata.Message}", true);
        }
Example #8
0
 /// <summary>
 /// 验证失败返回值
 /// </summary>
 /// <param name="context"></param>
 /// <param name="modelStates"></param>
 /// <param name="validationResults"></param>
 /// <param name="validateFailedMessage"></param>
 /// <returns></returns>
 public IActionResult OnValidateFailed(ActionExecutingContext context, ModelStateDictionary modelStates, Dictionary <string, IEnumerable <string> > validationResults, string validateFailedMessage)
 {
     return(new JsonResult(new ApiResponse <object>
     {
         Code = StatusCodes.Status400BadRequest,
         Success = false,
         Data = null,
         Msg = validationResults,
         Extras = UnifyContext.Take(),
         Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
     }));
 }
Example #9
0
 /// <summary>
 /// 异常返回值
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public IActionResult OnException(ExceptionContext context)
 {
     // 解析异常信息
     var(StatusCode, Errors) = UnifyContext.GetExceptionMetadata(context);
     return(new JsonResult(new ApiResponse <object>
     {
         Code = StatusCode,
         Success = false,
         Data = null,
         Msg = Errors,
         Extras = UnifyContext.Take(),
         Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
     }));
 }
        /// <summary>
        /// 异常返回值
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public IActionResult OnException(ExceptionContext context)
        {
            // 解析异常信息
            var(StatusCode, ErrorCode, Errors) = UnifyContext.GetExceptionMetadata(context);

            return(new JsonResult(new RESTfulResult <object>
            {
                Code = StatusCode,
                Succeeded = false,
                Data = null,
                Msg = context.Exception is AppFriendlyException ? Errors : "系统异常,请联系管理员",//Errors
                Extras = UnifyContext.Take(),
                Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            }));
        }
Example #11
0
        /// <summary>
        /// 处理输出状态码
        /// </summary>
        /// <param name="context"></param>
        /// <param name="statusCode"></param>
        /// <returns></returns>
        public async Task OnResponseStatusCodes(HttpContext context, int statusCode)
        {
            switch (statusCode)
            {
            // 处理 401 状态码
            case StatusCodes.Status401Unauthorized:
                await context.Response.WriteAsJsonAsync(new ApiResponse <object>
                {
                    Code      = StatusCodes.Status401Unauthorized,
                    Success   = false,
                    Data      = null,
                    Msg       = "401 Unauthorized",
                    Extras    = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                }, JsonSerializerUtility.GetDefaultJsonSerializerOptions());

                break;

            // 处理 403 状态码
            case StatusCodes.Status403Forbidden:
                await context.Response.WriteAsJsonAsync(new ApiResponse <object>
                {
                    Code      = StatusCodes.Status403Forbidden,
                    Success   = false,
                    Data      = null,
                    Msg       = "403 Forbidden",
                    Extras    = UnifyContext.Take(),
                    Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                }, JsonSerializerUtility.GetDefaultJsonSerializerOptions());

                break;

            default:
                break;
            }
        }
Example #12
0
 /// <summary>
 /// 设置异常状态码
 /// </summary>
 /// <param name="exception"></param>
 /// <param name="statusCode"></param>
 /// <returns></returns>
 public static Exception StatusCode(this Exception exception, int statusCode = StatusCodes.Status500InternalServerError)
 {
     UnifyContext.Set(UnifyContext.UnifyResultStatusCodeKey, statusCode);
     return(exception);
 }
Example #13
0
        /// <summary>
        /// 异常拦截
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            // 解析异常处理服务,实现自定义异常额外操作,如记录日志等
            var globalExceptionHandler = context.HttpContext.RequestServices.GetService <IGlobalExceptionHandler>();

            if (globalExceptionHandler != null)
            {
                await globalExceptionHandler.OnExceptionAsync(context);
            }

            // 如果异常在其他地方被标记了处理,那么这里不再处理
            if (context.ExceptionHandled)
            {
                return;
            }

            // 获取控制器信息
            var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;

            // 解析异常信息
            var exceptionMetadata = UnifyContext.GetExceptionMetadata(context);

            // 判断是否是验证异常
            var isValidationException = context.Exception is AppFriendlyException friendlyException && friendlyException.ValidationException;

            // 判断是否跳过规范化结果,如果是,则只处理为友好异常消息
            if (UnifyContext.CheckFailedNonUnify(actionDescriptor.MethodInfo, out var unifyResult))
            {
                // 如果是验证异常,返回 400
                if (isValidationException)
                {
                    context.Result = new BadRequestResult();
                }
                else
                {
                    // 返回友好异常
                    context.Result = new ContentResult()
                    {
                        Content    = exceptionMetadata.Errors.ToString(),
                        StatusCode = exceptionMetadata.StatusCode
                    };
                }
            }
            else
            {
                // 判断是否支持 MVC 规范化处理
                if (!UnifyContext.CheckSupportMvcController(context.HttpContext, actionDescriptor, out _))
                {
                    return;
                }

                // 执行规范化异常处理
                context.Result = unifyResult.OnException(context, exceptionMetadata);
            }

            // 判断异常消息是否是验证异常(比如数据验证异常,业务抛出异常)
            if (isValidationException)
            {
                // 解析验证消息
                var validationMetadata = ValidatorContext.GetValidationMetadata((context.Exception as AppFriendlyException).ErrorMessage);

                App.PrintToMiniProfiler("Validation", "Failed", $"Validation Failed:\r\n{validationMetadata.Message}", true);
            }
            else
            {
                PrintToMiniProfiler(context.Exception);
            }
        }
 public void TestContextCreate()
 {
     using (var db = new UnifyContext())
     {
     }
 }