public static string MapPath(this HttpContext httpContext, string virtualPath)
        {
            UrlHelper urlHelper = new UrlHelper(AutofacHelper.GetScopeService <IActionContextAccessor>().ActionContext);

            virtualPath = urlHelper.Content(virtualPath);

            return($"{Path.Combine(new List<string> { GlobalSwitch.WebRootPath }.Concat(virtualPath.Split('/')).ToArray())}");
        }
Exemplo n.º 2
0
        /// <summary>
        /// Action执行之前执行
        /// </summary>
        /// <param name="filterContext">过滤器上下文</param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            IPermissionManage    PermissionManage    = AutofacHelper.GetScopeService <IPermissionManage>();
            IUrlPermissionManage UrlPermissionManage = AutofacHelper.GetScopeService <IUrlPermissionManage>();

            //若为本地测试,则不需要校验
            if (GlobalSwitch.RunModel == RunModel.LocalTest)
            {
                return;
            }
            AjaxResult res = new AjaxResult();

            //判断是否需要校验
            if (filterContext.ContainsFilter <IgnoreAppIdPermissionAttribute>())
            {
                return;
            }

            var allRequestParams = HttpHelper.GetAllRequestParams(filterContext.HttpContext);

            if (!allRequestParams.ContainsKey("appId"))
            {
                res.Success          = false;
                res.Msg              = "缺少appId参数!";
                filterContext.Result = new ContentResult {
                    Content = res.ToJson()
                };

                return;
            }
            string appId             = allRequestParams["appId"]?.ToString();
            var    allUrlPermissions = UrlPermissionManage.GetAllUrlPermissions();
            string requestUrl        = filterContext.HttpContext.Request.Path;
            var    thePermission     = allUrlPermissions.Where(x => requestUrl.Contains(x.Url.ToLower())).FirstOrDefault();

            if (thePermission == null)
            {
                return;
            }
            string needPermission = thePermission.PermissionValue;
            bool   hasPermission  = PermissionManage.GetAppIdPermissionValues(appId).Any(x => x.ToLower() == needPermission.ToLower());

            if (hasPermission)
            {
                return;
            }
            else
            {
                res.Success          = false;
                res.Msg              = "权限不足!访问失败!";
                filterContext.Result = new ContentResult {
                    Content = res.ToJson()
                };
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// 获取Url
        /// </summary>
        /// <param name="virtualUrl">虚拟Url</param>
        /// <returns></returns>
        public static string GetUrl(string virtualUrl)
        {
            if (!virtualUrl.IsNullOrEmpty())
            {
                UrlHelper urlHelper = new UrlHelper(AutofacHelper.GetScopeService <IActionContextAccessor>().ActionContext);

                return(urlHelper.Content(virtualUrl));
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Action执行之前执行
        /// </summary>
        /// <param name="context">过滤器上下文</param>
        public async override Task OnActionExecuting(ActionExecutingContext context)
        {
            if (context.ContainsFilter <NoApiPermissionAttribute>())
            {
                return;
            }

            IPermissionBusiness permissionBus = AutofacHelper.GetScopeService <IPermissionBusiness>();
            var permissions = await permissionBus.GetUserPermissionValuesAsync(Operator.UserId);

            if (!permissions.Contains(_permissionValue))
            {
                context.Result = Error("权限不足!");
            }
        }
Exemplo n.º 5
0
        public void OnException(ExceptionContext context)
        {
            ILogger logger = AutofacHelper.GetScopeService <ILogger>();

            var ex = context.Exception;

            logger.Error(ex);

            context.Result = new ContentResult
            {
                Content = new AjaxResult {
                    Success = false, Msg = ex.Message
                }.ToJson(),
                ContentType = "application/json; charset=utf-8",
            };
        }
Exemplo n.º 6
0
        public void OnException(ExceptionContext context)
        {
            ILogger logger = AutofacHelper.GetScopeService <ILogger>();

            var ex = context.Exception;

            if (ex is BusException busEx)
            {
                logger.Info(LogType.系统跟踪, busEx.Message);
                context.Result = Error(busEx.Message, busEx.ErrorCode);
            }
            else
            {
                logger.Error(ex);
                context.Result = Error(ex.Message);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Action执行之前执行
        /// </summary>
        /// <param name="filterContext">过滤器上下文</param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            IPermissionManage    PermissionManage    = AutofacHelper.GetScopeService <IPermissionManage>();
            IUrlPermissionManage UrlPermissionManage = AutofacHelper.GetScopeService <IUrlPermissionManage>();

            //若为本地测试,则不需要校验
            if (GlobalSwitch.RunModel == RunModel.LocalTest)
            {
                return;
            }

            //判断是否需要校验
            if (filterContext.ContainsFilter <IgnoreUrlPermissionAttribute>())
            {
                return;
            }

            var    allUrlPermissions = UrlPermissionManage.GetAllUrlPermissions();
            string requestUrl        = filterContext.HttpContext.Request.Path;
            var    thePermission     = allUrlPermissions.Where(x => requestUrl.ToLower().Contains(x.Url.ToLower())).FirstOrDefault();

            if (thePermission == null)
            {
                return;
            }
            string needPermission = thePermission.PermissionValue;
            bool   hasPermission  = PermissionManage.GetOperatorPermissionValues().Any(x => x.ToLower() == needPermission.ToLower());

            if (hasPermission)
            {
                return;
            }
            else
            {
                AjaxResult res = new AjaxResult
                {
                    Success = false,
                    Msg     = "权限不足!无法访问!"
                };
                filterContext.Result = new ContentResult {
                    Content = res.ToJson(), ContentType = "application/json;charset=utf-8"
                };
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// 压力测试
        /// </summary>
        /// <returns></returns>
        public ActionResult PressTest()
        {
            var           bus  = AutofacHelper.GetScopeService <IBase_UserBusiness>();
            var           db   = DbFactory.GetRepository();
            Base_UnitTest data = new Base_UnitTest
            {
                Id       = Guid.NewGuid().ToString(),
                UserId   = Guid.NewGuid().ToString(),
                Age      = 10,
                UserName = Guid.NewGuid().ToString()
            };

            db.Insert(data);
            db.Update(data);
            db.GetIQueryable <Base_UnitTest>().FirstOrDefault();
            db.Delete(data);

            return(Success(""));
        }
Exemplo n.º 9
0
        /// <summary>
        /// 根据配置文件获取数据库类型,并返回对应的工厂接口
        /// </summary>
        /// <param name="conString">链接字符串</param>
        /// <param name="dbType">数据库类型</param>
        /// <returns></returns>
        public static IRepository GetRepository(string conString = null, DatabaseType?dbType = null)
        {
            conString = conString.IsNullOrEmpty() ? GlobalSwitch.DefaultDbConName : conString;
            conString = DbProviderFactoryHelper.GetConStr(conString);
            dbType    = dbType.IsNullOrEmpty() ? GlobalSwitch.DatabaseType : dbType;
            Type dbRepositoryType = Type.GetType("Coldairarrow.DataRepository." + DbProviderFactoryHelper.DbTypeToDbTypeStr(dbType.Value) + "Repository");

            var repository = Activator.CreateInstance(dbRepositoryType, new object[] { conString }) as IRepository;

            //请求结束自动释放
            try
            {
                AutofacHelper.GetScopeService <IDisposableContainer>().AddDisposableObj(repository);
            }
            catch
            {
            }

            return(repository);
        }
Exemplo n.º 10
0
        public async Task PressTest2()
        {
            var bus = AutofacHelper.GetScopeService <IBase_UserBusiness>();

            using (var db = DbFactory.GetRepository())
            {
                Base_UnitTest data = new Base_UnitTest
                {
                    Id       = Guid.NewGuid().ToString(),
                    UserId   = Guid.NewGuid().ToString(),
                    Age      = 10,
                    UserName = Guid.NewGuid().ToString()
                };
                await db.InsertAsync(data);

                await db.UpdateAsync(data);

                await db.GetIQueryable <Base_UnitTest>().FirstOrDefaultAsync();

                await db.DeleteAsync(data);
            }
        }
        /// <summary>
        /// Action执行之前执行
        /// </summary>
        /// <param name="filterContext">过滤器上下文</param>
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            IOperator Operator = AutofacHelper.GetScopeService <IOperator>();
            ILogger   logger   = AutofacHelper.GetScopeService <ILogger>();

            var request = filterContext.HttpContext.Request;

            try
            {
                //若为本地测试,则不需要登录
                if (GlobalSwitch.RunModel == RunModel.LocalTest)
                {
                    return;
                }

                //判断是否需要登录
                if (filterContext.ContainsFilter <IgnoreLoginAttribute>())
                {
                    return;
                }

                //转到登录
                if (!Operator.Logged())
                {
                    RedirectToLogin();
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                RedirectToLogin();
            }

            void RedirectToLogin()
            {
                if (request.IsAjaxRequest())
                {
                    filterContext.Result = new ContentResult
                    {
                        Content = new AjaxResult {
                            Success = false, ErrorCode = 1, Msg = "未登录"
                        }.ToJson(),
                        ContentType = "application/json;charset=UTF-8"
                    };
                }
                else
                {
                    UrlHelper urlHelper = new UrlHelper(filterContext);
                    string    loginUrl  = urlHelper.Content("~/Home/Login");
                    string    script    = $@"    
<html>
    <script>
        top.location.href = '{loginUrl}';
    </script>
</html>
";
                    filterContext.Result = new ContentResult {
                        Content = script, ContentType = "text/html"
                    };
                }
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Action执行之前执行
        /// </summary>
        /// <param name="filterContext"></param>
        public async override Task OnActionExecuting(ActionExecutingContext filterContext)
        {
            IBase_AppSecretBusiness appSecretBus = AutofacHelper.GetScopeService <IBase_AppSecretBusiness>();
            ILogger logger = AutofacHelper.GetScopeService <ILogger>();

            //若为本地测试,则不需要校验
            if (GlobalSwitch.RunMode == RunMode.LocalTest)
            {
                return;
            }

            //判断是否需要签名
            if (filterContext.ContainsFilter <IgnoreSignAttribute>())
            {
                return;
            }

            var    request = filterContext.HttpContext.Request;
            string appId   = request.Headers["appId"].ToString();

            if (appId.IsNullOrEmpty())
            {
                ReturnError("缺少header:appId");
                return;
            }
            string time = request.Headers["time"].ToString();

            if (time.IsNullOrEmpty())
            {
                ReturnError("缺少header:time");
                return;
            }
            if (time.ToDateTime() < DateTime.Now.AddMinutes(-5) || time.ToDateTime() > DateTime.Now.AddMinutes(5))
            {
                ReturnError("time过期");
                return;
            }

            string guid = request.Headers["guid"].ToString();

            if (guid.IsNullOrEmpty())
            {
                ReturnError("缺少header:guid");
                return;
            }

            string guidKey = $"{GlobalSwitch.ProjectName}_apiGuid_{guid}";

            if (CacheHelper.Cache.GetCache(guidKey).IsNullOrEmpty())
            {
                CacheHelper.Cache.SetCache(guidKey, "1", new TimeSpan(0, 10, 0));
            }
            else
            {
                ReturnError("禁止重复调用!");
                return;
            }

            string body = request.Body.ReadToString();

            string sign = request.Headers["sign"].ToString();

            if (sign.IsNullOrEmpty())
            {
                ReturnError("缺少header:sign");
                return;
            }

            string appSecret = await appSecretBus.GetAppSecretAsync(appId);

            if (appSecret.IsNullOrEmpty())
            {
                ReturnError("header:appId无效");
                return;
            }

            string newSign = HttpHelper.BuildApiSign(appId, appSecret, guid, time.ToDateTime(), body);

            if (sign != newSign)
            {
                string log =
                    $@"header:sign签名错误!
headers:{request.Headers.ToJson()}
body:{body}
正确sign:{newSign}
";
                logger.Error(LogType.系统异常, log);
                ReturnError("header:sign签名错误");
                return;
            }

            void ReturnError(string msg)
            {
                filterContext.Result = Error(msg);
            }
        }