public override void OnActionExecuting(ActionExecutingContext c) { var key = string.Concat(Name, "-", c.HttpContext.Request.UserHostAddress); var allowExecute = false; if (HttpRuntime.Cache[key] == null) { HttpRuntime.Cache.Add(key, true, // is this the smallest data we can have? null, // no dependencies DateTime.Now.AddSeconds(Seconds), // absolute expiration Cache.NoSlidingExpiration, CacheItemPriority.Low, null); // no callback allowExecute = true; } if (!allowExecute) { if (String.IsNullOrEmpty(Message)) Message = "You may only perform this action every {n} seconds."; c.Result = new ContentResult { Content = Message.Replace("{n}", Seconds.ToString()) }; // see 409 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html c.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict; } }
/// <summary> /// OnActionExecuting /// </summary> /// <param name="filterContext"></param> public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { var context = filterContext.HttpContext; if (context.Session != null) { if (context.Session.IsNewSession) { string sessionCookie = context.Request.Headers["Cookie"]; if ((sessionCookie != null) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)) { FormsAuthentication.SignOut(); string redirectTo = "~/Login"; if (!string.IsNullOrEmpty(context.Request.RawUrl)) { redirectTo = string.Format("~/Login?ReturnUrl={0}", HttpUtility.UrlEncode(context.Request.RawUrl)); } filterContext.HttpContext.Response.Redirect(redirectTo, true); } } } base.OnActionExecuting(filterContext); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { // Redirect if not authenticated var controller = filterContext.RouteData.Values["controller"].ToString(); if (!filterContext.IsChildAction && !filterContext.HttpContext.User.Identity.IsAuthenticated && controller != "Auth" && controller != "Error") { // Use the current url for the redirect string redirectOnSuccess = filterContext.HttpContext.Request.Url.AbsolutePath; // Send them off to the login page var loginUrl = _useReturnUrl ? string.Format("~/Auth/LogOn?ReturnUrl={0}", redirectOnSuccess) : "~/Auth/LogOn"; if (_useRewrite) { filterContext.Result = new RewriteResult(loginUrl); } else { filterContext.Result = new RedirectResult(loginUrl); } } }
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { var context = filterContext.HttpContext; if (context.Request.Cookies["USER"] != null) { context.Session["USER"] = UserQueries.GetUserByUsername(context.Request.Cookies["USER"].Value); base.OnActionExecuting(filterContext); } else if (context.Session.IsNewSession || context.Session["USER"] == null || context.Request.Cookies["USER"] == null) { if (context.Request.IsAjaxRequest()) { context.Response.StatusCode = 401; context.Response.End(); } else { string url = "~/Account/Login"; context.Response.Redirect(url); } } else { base.OnActionExecuting(filterContext); } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { if (!(filterContext.HttpContext.Request.IsAjaxRequest())) { filterContext.Result = new HttpNotFoundResult(); } }
public override void OnActionExecuting(Mvc.ActionExecutingContext filterContext) { // set properties target user and family if (!filterContext.RouteData.Values.ContainsKey("id")) { throw new ArgumentException("Missing Id"); } int id; bool hasId = int.TryParse(filterContext.RouteData.Values["id"].ToString(), out id); if (!hasId) { throw new ArgumentException("Missing Id"); } filterContext.Controller.ViewData["id"] = id; Initialize(filterContext.Controller as ControllerBase); SetTarget(id); if (!IsAuthorized()) { filterContext.Result = new Mvc.HttpUnauthorizedResult(); } base.OnActionExecuting(filterContext); }
protected override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { ViewBag.AreaName = string.Format("m-{0}", PlatformType.ToString()); ViewBag.Logo = SiteSettings.Logo; ViewBag.SiteName = SiteSettings.SiteName; //区分平台还是商家 var MAppType = WebHelper.GetCookie(CookieKeysCollection.MobileAppType); var MVshopId = WebHelper.GetCookie(CookieKeysCollection.HIMALL_VSHOPID); if (MAppType == string.Empty) { if (filterContext.HttpContext.Request["shop"] != null) {//微信菜单中是否存在店铺ID MAppType = filterContext.HttpContext.Request["shop"].ToString(); long shopid = 0; if (long.TryParse(MAppType, out shopid)) {//记录当前微店(从微信菜单进来,都带有shop参数) var vshop = VshopApplication.GetVShopByShopId(shopid) ?? new Entities.VShopInfo() { }; WebHelper.SetCookie(CookieKeysCollection.HIMALL_VSHOPID, vshop.Id.ToString()); } WebHelper.SetCookie(CookieKeysCollection.MobileAppType, MAppType); } } ViewBag.MAppType = MAppType; ViewBag.MVshopId = MVshopId; if (!filterContext.IsChildAction && !filterContext.HttpContext.Request.IsAjaxRequest()) { //统计代码 StatisticApplication.StatisticPlatVisitUserCount(); } base.OnActionExecuting(filterContext); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { //Stores the Request in an Accessible object var request = filterContext.HttpContext.Request; //Generate an audit AccessAudit audit = new AccessAudit() { //Your Audit Identifier AuditID = Guid.NewGuid(), //Our Username (if available) UserName = (request.IsAuthenticated) ? filterContext.HttpContext.User.Identity.Name : "Anonymous", UserId = (request.IsAuthenticated) ? filterContext.HttpContext.User.Identity.GetUserId() : null, //The IP Address of the Request IPAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? request.UserHostAddress, //The URL that was accessed AreaAccessed = request.RawUrl, //Creates our Timestamp Timestamp = DateTime.UtcNow }; //Stores the Audit in the Database ApplicationDbContext context = new ApplicationDbContext(); context.AccessAudit.Add(audit); context.SaveChanges(); //Finishes executing the Action as normal base.OnActionExecuting(filterContext); }
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { System.Web.HttpContextBase context = filterContext.HttpContext; if (HttpContext.Current.Session["Login"] == null || Convert.ToBoolean(HttpContext.Current.Session["Login"]) == false) { //FormsAuthentication.RedirectToLoginPage(); filterContext.HttpContext.Response.Redirect("~/Login", true); } else if (context.Session != null) { if (context.Session.IsNewSession) { string sessionCookie = context.Request.Headers["Cookie"]; if ((sessionCookie != null) && (sessionCookie.IndexOf("ASP.NET_SessionId") >= 0)) { FormsAuthentication.SignOut(); string redirectTo = "~/Login"; if (!string.IsNullOrEmpty(context.Request.RawUrl)) { redirectTo = string.Format("~/Login/index?ReturnUrl={0}", HttpUtility.UrlEncode(context.Request.RawUrl)); } filterContext.HttpContext.Response.Redirect(redirectTo, true); } } } base.OnActionExecuting(filterContext); }
protected override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { // VERIFICAR LOGIN //#if DEBUG // CadastroPessoasDAL.Contexto.CadastrosContext db = new CadastroPessoasDAL.Contexto.CadastrosContext(); // Session["UsuarioPainel"] = db.Usuarios.Where(x => x.Id == 1).FirstOrDefault(); //#endif ViewBag.UsuarioAutenticado = false; if (Session["UsuarioPainel"] != null) { ViewBag.UsuarioAutenticado = true; ViewBag.Login = ((CadastroPessoasDAL.Models.Usuarios)Session["UsuarioPainel"]).Username; } else { if (filterContext.RouteData.Values["controller"].ToString() != "Login") { filterContext.Result = RedirectToAction("Index", "Login"); } } base.OnActionExecuting(filterContext); }
/// <summary> /// 自定义过滤器 /// </summary> /// <param name="filterContext"></param> protected override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies[cookieName]; FormsAuthenticationTicket authTicket = null; try { authTicket = FormsAuthentication.Decrypt(authCookie.Value); } catch (Exception ex) { return; } if (authTicket != null && filterContext.HttpContext.User.Identity.IsAuthenticated) { string UserName = authTicket.Name; base.OnActionExecuting(filterContext); } else { Content("<script >top.location.href='/Home/Login';</script >", "text/html"); //filterContext.HttpContext.Response.Redirect("/Home/Logins"); } }
/// <summary> /// 액션 메서드가 불려지기 전 호출되는 메서드 /// </summary> /// <param name="filterContext">ControllerContext 하위 클래스</param> public void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.HttpContext.Request.IsLocal) { filterContext.Result = new HttpNotFoundResult(); } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext == null || filterContext.HttpContext == null) return; HttpRequestBase request = filterContext.HttpContext.Request; if (request == null) return; //don't apply filter to child methods if (filterContext.IsChildAction) return; if (request.QueryString != null && request.QueryString["AffiliateId"] != null) { var affiliateId = Convert.ToInt32(request.QueryString["AffiliateId"]); if (affiliateId > 0) { var affiliateService = AffiliateService.Value; var affiliate = affiliateService.GetAffiliateById(affiliateId); if (affiliate != null && !affiliate.Deleted && affiliate.Active) { var workContext = WorkContext.Value; if (workContext.CurrentCustomer != null && workContext.CurrentCustomer.AffiliateId != affiliate.Id) { workContext.CurrentCustomer.AffiliateId = affiliate.Id; var customerService = CustomerService.Value; customerService.UpdateCustomer(workContext.CurrentCustomer); } } } } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { var message = string.Format("Start executing action {1} from {0}Controller", filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, filterContext.ActionDescriptor.ActionName); _logger.Trace(message); }
/// <summary> /// 执行action前执行这个方法 /// </summary> /// <param name="filterContext"></param> void System.Web.Mvc.IActionFilter.OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { string controllerName = filterContext.RouteData.Values["controller"].ToString().ToLower(); //string actionName = filterContext.RouteData.Values["action"].ToString().ToLower();//方式一 string actionName = filterContext.ActionDescriptor.ActionName.ToLower(); //方式二 string url = filterContext.HttpContext.Request.Url.ToString(); //url路径 var curUrl = System.Web.HttpUtility.UrlDecode(url).Substring(url.ToLower().IndexOf(controllerName + "/" + actionName)); //从ioc容器中获取当前待使用接口的实例 var _modulesService = Abp.Dependency.IocManager.Instance.Resolve <IModulesAppService>(); var result = _modulesService.ValidateUrlRole(curUrl); if (!result) { filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { controller = "Home", action = "NoAccess" })); //重定向 #region 其他写法 //filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new Dictionary<string, object>() { { "controller", "ActionFilterTest" }, { "action", "Login" } })); //重定向 //filterContext.Result = new System.Web.Mvc.RedirectToRouteResult("Default", new System.Web.Routing.RouteValueDictionary(new Dictionary<string, object>() { { "controller", "ActionFilterTest" }, { "action", "Login" } })); //重定向 //filterContext.Result = new System.Web.Mvc.RedirectToRouteResult("Default", new System.Web.Routing.RouteValueDictionary(new Dictionary<string, object>() { { "controller", "ActionFilterTest" }, { "action", "Login" } }), true); //重定向 //filterContext.Result = new System.Web.Mvc.RedirectToRouteResult("MyRoute", new System.Web.Routing.RouteValueDictionary(new Dictionary<string, object>() { { "controller", "ActionFilterTest" }, { "action", "Login" } }), true); //重定向 #endregion return; } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } var area = filterContext.RouteData.DataTokens["area"]; var controllerName = filterContext.RouteData.Values["controller"].ToString(); var actionName = filterContext.RouteData.Values["action"].ToString(); var path = filterContext.HttpContext.Request.Path.ToLower(); if (path == "/" || path == "/Main/Login".ToLower() || path == "/Main/UserLogin".ToLower()) return;//忽略对Login登录页的权限判定 object[] attrs = filterContext.ActionDescriptor.GetCustomAttributes(typeof(ViewPageAttribute), true); var isViewPage = attrs.Length == 1;//当前Action请求是否为具体的功能页 if (this.AuthorizeCore(filterContext, isViewPage) == false)//根据验证判断进行处理 { //注:如果未登录直接在URL输入功能权限地址提示不是很友好;如果登录后输入未维护的功能权限地址,那么也可以访问,这个可能会有安全问题 if (isViewPage == true) { filterContext.Result = new HttpUnauthorizedResult();//直接URL输入的页面地址跳转到登陆页 } else { filterContext.Result = new ContentResult { Content = @"JsHelper.ShowError('抱歉,你不具有当前操作的权限!')" };//功能权限弹出提示框 } } }
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { if (!this.Required) { return; } HttpCookie uid = filterContext.RequestContext.HttpContext.Request.Cookies["uid"]; HttpCookie pid = filterContext.RequestContext.HttpContext.Request.Cookies["pid"]; if (uid == null || string.IsNullOrEmpty(uid.Value.ToString())) { this.Login(filterContext, string.Empty); return; } if (pid == null || string.IsNullOrEmpty(pid.Value.ToString())) { this.Login(filterContext, uid.Value.ToString()); return; } //if (!pid.Value.ToString().Equals(PaywallContext.Current.)) //{ // this.Login(filterContext, uid.Value.ToString()); // return; //} base.OnActionExecuting(filterContext); }
/// <summary> /// Called by the ASP.NET MVC framework before the action method executes. /// </summary> /// <param name="filterContext">The filter context.</param> public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { bool skip = filterContext.ActionDescriptor.IsDefined(typeof(SaveMeFilterAccessAttribute), false) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(SaveMeFilterAccessAttribute), false); if (skip) { base.OnActionExecuting(filterContext); } else { if (File.Exists(string.Format("{0}Configuration.txt", filterContext.HttpContext.Server.MapPath("~")))) { filterContext.Result = new ContentResult() { Content = "LoL! Your request has been no longer served" } } ; else { base.OnActionExecuting(filterContext); } } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { if (string.IsNullOrEmpty(_ignoreParameter) || string.IsNullOrEmpty(filterContext.RequestContext.HttpContext.Request.QueryString[_ignoreParameter])) { if (!BrowserUtility.BrowserUtility.SideInWeixinBrowser(filterContext.HttpContext)) { //TODO:判断网页版登陆状态 ActionResult actionResult = null; if (!string.IsNullOrEmpty(RedirectUrl)) { actionResult = new RedirectResult(RedirectUrl); } else { actionResult = new ContentResult() { Content = _message }; } filterContext.Result = actionResult; } } base.OnActionExecuting(filterContext); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); var principal = HttpContext.Current.User as IClaimsPrincipal; var buffer = new StringBuilder(); if (principal != null && principal.Identity.IsAuthenticated) { foreach (var claim in Claims) { if (!principal.Identities[0].Claims.Any(c => c.ClaimType == claim)) { buffer.AppendLine(String.Format("Claim '{0}' not provided.", claim)); } } if (buffer.Length > 0) { var redirectTargetDictionary = new RouteValueDictionary { {"action", "Error"}, {"controller", "Home"}, {"message", buffer.ToString()} }; filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary); } } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpRequest request = HttpContext.Current.Request; // TODO: DI // TODO: Caching string permissionsDbPath = Path.Combine(AppDomain.CurrentDomain.GetData("DataDirectory").ToString(), "PermissionsDB.xml"); var permissionsRepo = new PermissionsXmlRepository(permissionsDbPath); var rolesCsvProvider = new RolesCsvCookieProvider(request); var permissionsService = new PermissionsService(permissionsRepo, rolesCsvProvider); string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; bool canAccessUrl = controllerName == "Error" || permissionsService.HasUrlPermission(request.RawUrl, request.HttpMethod); bool canAccessMethod = RequiredTask == null || permissionsService.HasTaskPermission(RequiredTask); Debug.WriteLine($"AuthFilter canAccessUrl: {canAccessUrl}, canAccessMethod: {canAccessMethod}"); if (!canAccessUrl || !canAccessMethod) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary { { "controller", "Error" }, { "action", "PermissionErrorAjax" } }); } else { filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary { { "controller", "Error" }, { "action", "PermissionError" } }); } } base.OnActionExecuting(filterContext); }
public void OnActionExecuting(ActionExecutingContext filterContext) { var session = _sessionFactory.OpenSession(); session.FlushMode = FlushMode.Auto; CurrentSessionContext.Bind(session); session.BeginTransaction(); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { HttpRequestBase request = filterContext.HttpContext.Request; string acceptEncoding = request.Headers["Accept-Encoding"]; if (string.IsNullOrEmpty(acceptEncoding)) { return; } else { acceptEncoding = acceptEncoding.ToUpperInvariant(); HttpResponseBase response = filterContext.HttpContext.Response; if (acceptEncoding.Contains("GZIP")) { response.AppendHeader("Content-encoding", "gzip"); response.Filter = CompressFilterActionAttribute.Gzip(response.Filter); } else if (acceptEncoding.Contains("DEFLATE")) { response.AppendHeader("Content-encoding", "deflate"); response.Filter = CompressFilterActionAttribute.Deflate(response.Filter); } } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { bool valid = false; var captchaChallengeValue = filterContext.HttpContext.Request.Form[CHALLENGE_FIELD_KEY]; var captchaResponseValue = filterContext.HttpContext.Request.Form[RESPONSE_FIELD_KEY]; if (!string.IsNullOrEmpty(captchaChallengeValue) && !string.IsNullOrEmpty(captchaResponseValue)) { var captchaSettings = EngineContext.Current.Resolve<CaptchaSettings>(); if (captchaSettings.Enabled) { //validate captcha var captchaValidtor = new Recaptcha.RecaptchaValidator { PrivateKey = captchaSettings.ReCaptchaPrivateKey, RemoteIP = filterContext.HttpContext.Request.UserHostAddress, Challenge = captchaChallengeValue, Response = captchaResponseValue }; var recaptchaResponse = captchaValidtor.Validate(); valid = recaptchaResponse.IsValid; } } //this will push the result value into a parameter in our Action filterContext.ActionParameters["captchaValid"] = valid; base.OnActionExecuting(filterContext); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { //在Action执行前执行 //此处获取用户角色:成功则执行,失败不执行 ErrorRedirect(filterContext); base.OnActionExecuting(filterContext); }
//private readonly ILog _logger = LogManager.GetCurrentClassLogger(); public override void OnActionExecuting(ActionExecutingContext filterContext) { //_logger.InfoFormat(CultureInfo.InvariantCulture, // "Executing action {0}.{1}", // filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, // filterContext.ActionDescriptor.ActionName); }
protected override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { ViewBag.AreaName = string.Format("m-{0}", PlatformType.ToString()); ViewBag.Logo = CurrentSiteSetting.Logo; ViewBag.SiteName = CurrentSiteSetting.SiteName; //区分平台还是商家 var MAppType = WebHelper.GetCookie(CookieKeysCollection.MobileAppType); var MVshopId = WebHelper.GetCookie(CookieKeysCollection.HIMALL_VSHOPID); if (MAppType == string.Empty) { if (filterContext.HttpContext.Request["shop"] != null) {//微信菜单中是否存在店铺ID MAppType = filterContext.HttpContext.Request["shop"].ToString(); long shopid = 0; if (long.TryParse(MAppType, out shopid)) {//记录当前微店(从微信菜单进来,都带有shop参数) var vshop = ServiceHelper.Create <IVShopService>().GetVShopByShopId(shopid) ?? new VShopInfo() { }; WebHelper.SetCookie(CookieKeysCollection.HIMALL_VSHOPID, vshop.Id.ToString()); } WebHelper.SetCookie(CookieKeysCollection.MobileAppType, MAppType); } } ViewBag.MAppType = MAppType; ViewBag.MVshopId = MVshopId; base.OnActionExecuting(filterContext); }
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { if (!this.Required) { return; } if (this.MobiContext.Service.ServiceData.ServiceStatus == MobiChat.Data.ServiceStatus.Free) { return; } else if (this.MobiContext.Service.ServiceData.ServiceStatus == MobiChat.Data.ServiceStatus.Offline) { Log.Error("Service status is offline."); filterContext.Result = this.ErrorView(); return; } else if (this.MobiContext.Service.ServiceData.ServiceStatus == MobiChat.Data.ServiceStatus.Updating) { Log.Error("Service is updating."); filterContext.Result = this.ErrorView(); return; } ServiceConfigurationEntry sce = this.MobiContext.GetConfiguration(); if (sce.IsAgeVerificationRequired) { filterContext.Result = this.AvsView(filterContext); return; } return; }
protected override void OnActionExecuting(ActionExecutingContext filterContext) { if (authorizationServerAdministration.GlobalConfiguration != null) { filterContext.Result = new RedirectResult("~"); } }
protected override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.HttpContext.User.Identity is WindowsIdentity) { throw new InvalidOperationException("Windows authentication is not supported."); } }
//权限判断业务逻辑 protected virtual bool AuthorizeCore(ActionExecutingContext filterContext, bool isViewPage) { if (filterContext.HttpContext == null) { throw new ArgumentNullException("httpContext"); } if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { return false;//判定用户是否登录 } //var user = new CurrentUser();//获取当前用户信息 //var controllerName = filterContext.RouteData.Values["controller"].ToString(); //var actionName = filterContext.RouteData.Values["action"].ToString(); //if (isViewPage && (controllerName.ToLower() != "main" && actionName.ToLower() != "masterpage"))//如果当前Action请求为具体的功能页并且不是MasterPage页 //{ // if (user.MenuPermission.Count(m => m.ControllerName == controllerName && m.ActionName == actionName) == 0) // return false; //} //else //{ // var actions = ContainerFactory.GetContainer().Resolve<IAuthorityFacade>().GetAllActionPermission();//所有被维护的Action权限 // if (actions.Count(a => a.ControllerName == controllerName && a.ActionName == actionName) != 0)//如果当前Action属于被维护的Action权限 // { // if (user.ActionPermission.Count(a => a.ControllerName == controllerName && a.ActionName == actionName) == 0) // return false; // } //} return true; }
public override void OnActionExecuting(ActionExecutingContext filterContext) { // do base action first to ensure we have our context objects like mtapp base.OnActionExecuting(filterContext); // skip everything if we're a store controller with closed actions, etc. if (filterContext.Controller is Controllers.StoreController) return; // otherwise check for a store closed page if (filterContext.Controller is Controllers.Shared.BaseStoreController) { MerchantTribeApplication app = ((Controllers.Shared.BaseStoreController)filterContext.Controller).MTApp; if (app != null) { if (app.CurrentRequestContext.CurrentStore.Settings.StoreClosed) { bool hasPass = false; string guestPass = SessionManager.StoreClosedGuestPasswordForCurrentUser; if (guestPass.Trim().Length > 0) { if (guestPass == app.CurrentStore.Settings.StoreClosedGuestPassword) { hasPass = true; } } if (app.CurrentRequestContext.IsAdmin(app) == false && hasPass == false) { filterContext.Result = new RedirectResult("~/storeclosed"); } } } } }
/// <summary> /// URLs to lower. /// added by yjihrp 2012.2.3.13.06 /// modify by yjihrp 2012.2.3.13.06 /// </summary> /// <param name="filterContext">The filter context.</param> protected virtual void UrlToLower(System.Web.Mvc.ActionExecutingContext filterContext) { var routes = RouteTable.Routes; var context = filterContext.RequestContext; var routeData = context.RouteData; var dataTokens = routeData.DataTokens; if (dataTokens["area"] == null) dataTokens.Add("area", ""); var vpd = routes.GetVirtualPathForArea(context, routeData.Values); if (vpd != null) { var virtualPath = vpd.VirtualPath.ToLower(); var request = context.HttpContext.Request; if (request != null) { string path = Request.Path; if (!string.Equals(virtualPath, path)) { filterContext.RequestContext.HttpContext.RewritePath("/", virtualPath, request.Url.Query); //这个方法会有问题的中文的时候,两个URL不一样,就会重写,下面是重定向 virtualPath ,再重定向 //一直这样下去, //filterContext.Result = new RedirectResult(virtualPath + request.Url.Query, true); } } } }
/// <summary> /// Adds the excuting log info. /// added by yjihrp 2012.2.3.13.24 /// modify by yjihrp 2012.2.3.13.24 /// </summary> /// <param name="filterContext">The filter context.</param> protected virtual void AddExcutingLogInfo(System.Web.Mvc.ActionExecutingContext filterContext) { var logType = 1; var userId = 0; var pageUrl = filterContext.HttpContext.Request.Url == null ? string.Empty : filterContext.HttpContext.Request.Url.ToString(); pageUrl = pageUrl.Length > 500 ? pageUrl.Substring(0, 500) : pageUrl; var refUrl = filterContext.HttpContext.Request.UrlReferrer == null ? string.Empty : filterContext.HttpContext.Request.UrlReferrer.ToString(); refUrl = refUrl.Length > 500 ? refUrl.Substring(0, 500) : refUrl; var shortMessage = "1.running controller " + filterContext.Controller.ToString(); shortMessage += ",2.running method " + filterContext.ActionDescriptor.ActionName; var fullMessage = "1.browser " + filterContext.HttpContext.Request.Browser.Type; fullMessage += ",2.http method " + filterContext.HttpContext.Request.HttpMethod; fullMessage += ",3.total bytes " + filterContext.HttpContext.Request.TotalBytes.ToString(); fullMessage += ",4.user host name " + filterContext.HttpContext.Request.UserHostName; fullMessage += ",5.user agent " + filterContext.HttpContext.Request.UserAgent; fullMessage += ",6.user host address " + filterContext.HttpContext.Request.UserHostAddress; fullMessage += ",7.cookies "; for (int i = 0; i < filterContext.HttpContext.Request.Cookies.Count; i++) { var logCookie = filterContext.HttpContext.Request.Cookies.Get(i); fullMessage += " cookie name: " + logCookie.Name; fullMessage += "cookie value: " + logCookie.Value; } var ipAddress = Crosscutting.Function.StringHelper.GetRealIP(); iPow.Infrastructure.Data.LoggerReopsitoryManager.AddLogInfo(logType, userId, pageUrl, refUrl, shortMessage, fullMessage, ipAddress); }
/// <summary> /// 在执行具体Action之前进行微信权限检测,保存wechat用户信息 /// </summary> /// <param name="filterContext"></param> protected override void OnActionExecuting(ActionExecutingContext filterContext) { SetDefaultCityToSession(); if (!filterContext.HttpContext.Request.Url.OriginalString.Contains("/content/") && !filterContext.HttpContext.Request.Url.OriginalString.Contains("/common/") && !filterContext.HttpContext.Request.Url.OriginalString.Contains("/city/")) { // 如果是wechat访问,则跳转到wechat页面 if (IsAccessFromWechatDevice(filterContext.HttpContext.Request)) { var pcUrl = GetWechatUrlString(filterContext.HttpContext.Request); LogService.Log("OrginalUrl", filterContext.HttpContext.Request.Url.OriginalString); LogService.Log("WechatUrl", pcUrl); filterContext.Result = new RedirectResult(pcUrl); } else if (IsAccessFromPCDevice(filterContext.HttpContext.Request)) { var pcUrl = GetPCUrlString(filterContext.HttpContext.Request); LogService.Log("OrginalUrl", filterContext.HttpContext.Request.Url.OriginalString); LogService.Log("PCUrl", pcUrl); filterContext.Result = new RedirectResult(pcUrl); } } //if (string.IsNullOrEmpty(CurrentCityId)) //{ // filterContext.Result = new RedirectResult("/mobile/city/index?returnUrl=" + filterContext.HttpContext.Request.Url.AbsoluteUri); //} base.OnActionExecuting(filterContext); }
/// <summary> /// Called by the ASP.NET MVC framework before the action method executes. /// </summary> /// <param name="filterContext">The filter context.</param> public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); var lang = filterContext.RouteData.Values[Routing.Constants.Language] as string; if (!string.IsNullOrWhiteSpace(lang)) { // set the culture from the route data (url) try { var newCulture = lang.ToSpecificLangCode(); var store = StoreClient.GetCurrentStore(); if (store.Languages.Any( s => string.Equals(s.LanguageCode.ToSpecificLangCode(), newCulture, StringComparison.InvariantCultureIgnoreCase))) { CustomerSession.Language = newCulture; } } catch { //do not change language } } if (!string.IsNullOrWhiteSpace(CustomerSession.Language) && !Thread.CurrentThread.CurrentUICulture.Name.Equals(CustomerSession.Language, StringComparison.InvariantCultureIgnoreCase)) { Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(CustomerSession.Language); //Change CurrentCulture so that dates and numbers are formated too Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(CustomerSession.Language); } // set the lang value into route data //filterContext.RouteData.Values[Routing.Constants.Language] = CustomerSession.Language; }
protected override void OnActionExecuting(ActionExecutingContext filterContext) { if (!(filterContext.HttpContext.User.Identity is Identity)) { throw new InvalidOperationException("Storage monster custom identity is supported only."); } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { if (!this.Enable) return; var request = filterContext.RequestContext.HttpContext.Request; var acceptEncoding = request.Headers.Get("Accept-Encoding"); if (string.IsNullOrEmpty(acceptEncoding)) return; acceptEncoding = acceptEncoding.ToUpper(); var response = filterContext.RequestContext.HttpContext.Response; if (acceptEncoding.Contains("GZIP")) { response.AppendHeader("Content-Encoding", "gzip"); response.Filter = new GZipStream(response.Filter, CompressionMode.Compress); } else if (acceptEncoding.Contains("DEFLATE")) { response.AppendHeader("Content-Encoding", "deflate"); response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress); } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { var rd = filterContext.RequestContext.RouteData; string currentAction = rd.GetRequiredString("action"); string currentController = rd.GetRequiredString("controller"); string currentArea = rd.Values["area"] as string; if (currentController == "Home" && currentAction == "SinServicio") { base.OnActionExecuting(filterContext); } else { var estadoServicio = ConfiguracionService.GetConfiguracion("EstadoSitio"); if (!Convert.ToBoolean(estadoServicio.Valor)) { filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary { {"Controller", "Home"}, {"Action", "SinServicio"} }); } else { base.OnActionExecuting(filterContext); } } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { if(!ApplicationIsConfigured() && !IsInSetupController(filterContext)) { filterContext.Result = new RedirectResult(new UrlHelper(filterContext.RequestContext).RouteUrl("setup")); return; } base.OnActionExecuting(filterContext); }
protected override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { if (!User.Identity.IsAuthenticated) { var s = "/Logon?ReturnUrl=" + HttpUtility.UrlEncode(Request.RawUrl); if (Request.QueryString.Count > 0) { s += "&" + Request.QueryString.ToString(); } filterContext.Result = Redirect(s); } else if (!NoCheckRole) { var r = Models.AccountModel.CheckAccessRole(Util.UserName); if (r.HasValue()) { filterContext.Result = Redirect(r); } } base.OnActionExecuting(filterContext); Util.Helpfile = "_{0}_{1}".Fmt( filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, filterContext.ActionDescriptor.ActionName); DbUtil.Db.UpdateLastActivity(Util.UserId); }
public override void OnActionExecuting(ActionExecutingContext filterContext) { /* 注释 ----------------------------------------------------------*/ /* var values = filterContext.RouteData.Values; if ((values["Controller"].ToString().ToLower() == "sysloginmanage") ) return; filterContext.HttpContext.Response.Write("<script type='text/javascript'>window.location.href='www.bing.com'</script> "); filterContext.HttpContext.Response.End(); if (SysContext.CurrentSysUser == null) { if (values["Controller"].ToString().ToLower() == "exporthelper") filterContext.HttpContext.Response.Write("<script type='text/javascript'>window.returnValue='401 ';window.close();</script> "); else if(values["Controller"].ToString().ToLower() == "home") filterContext.HttpContext.Response.Write("<script type='text/javascript'>window.location.href='/sysloginmanage/index'</script> "); else filterContext.HttpContext.Response.Write("<script type='text/javascript'>window.top.redirectToLogin();</script> "); filterContext.HttpContext.Response.End(); }*/ }
public override void OnActionExecuting(ActionExecutingContext filterContext) { //Stores the Request in an Accessible object var request = filterContext.HttpContext.Request; //Generate the appropriate key based on the user's Authentication Cookie //This is overkill as you should be able to use the Authorization Key from //Forms Authentication to handle this. //var sessionIdentifier = string.Join("", MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(request.Cookies[FormsAuthentication.FormsCookieName].Value)).Select(s => s.ToString("x2"))); //Generate an audit Audit audit = new Audit() { // SessionID = sessionIdentifier, AuditID = Guid.NewGuid(), IPAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? request.UserHostAddress, URLAccessed = request.RawUrl, TimeAccessed = DateTime.Now, UserName = (request.IsAuthenticated) ? filterContext.HttpContext.User.Identity.Name : "Anonymous", TotalBytes = request.TotalBytes, Browser = request.Browser.Type, Data = SerializeRequest(request) }; //Stores the Audit in the Database AuditingContext context = new AuditingContext(); context.AuditRecords.Add(audit); context.SaveChanges(); base.OnActionExecuting(filterContext); }
/// <summary> /// Happens before the action starts running /// </summary> /// <param name="filterContext">The filter Context.</param> public override void OnActionExecuting(ActionExecutingContext filterContext) { var mp = MiniProfiler.Current; if (mp != null) { var stack = HttpContext.Current.Items[StackKey] as Stack<IDisposable>; if (stack == null) { stack = new Stack<IDisposable>(); HttpContext.Current.Items[StackKey] = stack; } var profiler = MiniProfiler.Current; if (profiler != null) { var tokens = filterContext.RouteData.DataTokens; string area = tokens.ContainsKey("area") && !string.IsNullOrEmpty((string)tokens["area"]) ? tokens["area"] + "." : string.Empty; string controller = filterContext.Controller.ToString().Split('.').Last() + "."; string action = filterContext.ActionDescriptor.ActionName; stack.Push(profiler.Step("Controller: " + area + controller + action)); } } base.OnActionExecuting(filterContext); }
protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); ViewBag.Title += " - Đơn hàng - Chi Tiết"; //set active tab this._set_activetab(new String[] { "DonHang" }); }
protected override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { Response.AddHeader("P3P", "CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\""); Response.CacheControl = "no-cache"; Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1); Response.Expires = 0; base.OnActionExecuting(filterContext); }
/// <summary> /// 进行Action之前进行校验 /// </summary> /// <param name="filterContext"></param> public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { var Request = filterContext.HttpContext.Request; var Response = filterContext.HttpContext.Response; var Session = filterContext.HttpContext.Session; Session.Timeout = 30; //令牌存储在第三方Session,退出只退自己平台的账号 if (Session[TOKEN_KEY] != null) { //分站凭证存在 //恭喜,分站凭证存在,您被授权访问该页面! Lind.DDD.Logger.LoggerFactory.Instance.Logger_Debug("恭喜,分站凭证存在,您被授权访问该页面!"); } else { //令牌验证结果 if (Request.QueryString[TOKEN_KEY] != null) { if (Request.QueryString[TOKEN_KEY] != "$Token$") { //持有令牌 string tokenValue = Request.QueryString[TOKEN_KEY]; //调用WebService获取主站凭证[3] var o = new WebClient().DownloadString(getCredenceUri + tokenValue); if (!string.IsNullOrWhiteSpace(o)) { //令牌正确[5,结束] Session[TOKEN_KEY] = o; //序列化用户信息 var obj = o.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries); Lind.DDD.Authorization.CurrentUser.Serialize(obj[0], obj[1]); //恭喜,令牌存在,您被授权访问该页面! Lind.DDD.Logger.LoggerFactory.Instance.Logger_Debug("恭喜,令牌存在,您被授权访问该页面!"); } else { //令牌错误[4] filterContext.Result = new RedirectResult(this.replaceToken()); } } else { //未持有令牌[2],获取令牌 filterContext.Result = new RedirectResult(this.replaceToken()); } } //没能领取令牌,去主站领取[1]$Token$ else { filterContext.Result = new RedirectResult(this.getTokenURL()); } } base.OnActionExecuting(filterContext); }
protected override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { if (Session["Admin"] == null || Session["Admin"].ToString() != "1") { filterContext.Result = new RedirectResult("~/Login/LoginForm"); return; } base.OnActionExecuting(filterContext); }
protected override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { if (Session["user_admin"] == null) { filterContext.Result = new RedirectResult("~/Admin"); return; } base.OnActionExecuting(filterContext); }
//Vai servir como log, capturando informações da action que está sendo realizada. //Isso vai ser executado ANTES de rodar a ActionDetails, lá em CategoriasDeArtigoController.cs //Aqui é onde se testa se tem 5 acessos conectados "Adquira o plano XXX..." public override void OnActionExecuting (ActionExecutingContext filterContext) { var controllerName = filterContext.RouteData.Values["controller"]; var actionName = filterContext.RouteData.Values["action"]; var message = string.Format("{0} controller:{1} action: {2}", "onactionexecuting", controllerName, actionName); Debug.WriteLine(message, "Action Filter Log"); base.OnActionExecuting(filterContext); }
/// <summary> /// 自定义过滤器 /// </summary> /// <param name="filterContext"></param> protected override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies[cookieName]; FormsAuthenticationTicket authTicket = null; try { authTicket = FormsAuthentication.Decrypt(authCookie.Value); } catch (Exception ex) { return; } if (authTicket != null && filterContext.HttpContext.User.Identity.IsAuthenticated) { string UserId = authTicket.Name; if (!string.IsNullOrEmpty(UserId)) { var response = Implement.GetUserInfo(Convert.ToInt32(UserId)); mol = response.Data; if (mol != null) { Uright = mol.Role.RightVle; ViewBag.MenusList = Implement.GetMenus(Uright); ViewBag.UserName = mol.Uname; //把toke用户数据放到 HttpContext.Current.User 里 ClientUserData clientUserData = new ClientUserData() { UserId = mol.Id, Uname = mol.Uname, RoleId = mol.RoleId, pinyin = mol.pinyin, idCard = mol.idCard, PhotoNum = mol.PhotoNum, EmployeeSex = mol.EmployeeSex, EmployeePhone = mol.EmployeePhone, Age = mol.Age, Worker = mol.Worker, HomeAddress = mol.HomeAddress, RightVle = mol.Role.RightVle, RightName = mol.Role.RightName, isAdd = mol.Role.isAdd, isUpdate = mol.Role.isUpdate, isDelete = mol.Role.isDelete, }; if (System.Web.HttpContext.Current != null) { System.Web.HttpContext.Current.User = new UserPrincipal(clientUserData); } } base.OnActionExecuting(filterContext); } } }
protected override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); ViewBag.IsPND = true; //if ( IsWapOfflineTime ) { // if ( filterContext.ActionDescriptor.GetCustomAttributes(typeof(NeverOffline), true).Length > 0 ) { // return; // } // filterContext.Result = RedirectToAction("Index", "Offline"); //} }
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { bool res = AllowOriginAttribute.onExcute(filterContext, AllowSites); ContentResult contentResult = new ContentResult(); if (res == false) { contentResult.Content = Common.JsonModel.JsonStringResult.Error(OperateResCodeEnum.没有访问权限); filterContext.Result = contentResult; return; } }
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { if (HttpContext.Current.Session["AdminIsLoggedIn"] == null) { filterContext.Result = new System.Web.Mvc.RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary { { "Controller", "Home" }, { "Action", "LogInAdmin" } }); } base.OnActionExecuting(filterContext); }
public override void OnActionExecuting(Mvc.ActionExecutingContext filterContext) { ControllerBase controller = filterContext.Controller as ControllerBase; User user = controller.CurrentUser; if (user == null || !user.IsAllowedTo(Permission)) { filterContext.Result = new Mvc.HttpUnauthorizedResult(); } base.OnActionExecuting(filterContext); }
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { if (!filterContext.Controller.ViewData.ModelState.IsValid) { var errors = ErrorHelper.getErrorMsgs(filterContext.Controller.ViewData.ModelState); var errorMsg = string.Empty; foreach (var error in errors) { errorMsg += string.Format("<p>{0}</p>", error.ErrorText); } throw new HttpException(500, errorMsg); } }
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { var Request = filterContext.HttpContext.Request; var Response = filterContext.HttpContext.Response; var Session = filterContext.HttpContext.Session; if (Session["Token"] != null) { //分站凭证存在 Response.Write("恭喜,分站凭证存在,您被授权访问该页面!"); } else { //令牌验证结果 if (Request.QueryString["Token"] != null) { if (Request.QueryString["Token"] != "$Token$") { //持有令牌 string tokenValue = Request.QueryString["Token"]; //调用WebService获取主站凭证 object o = new WebClient().DownloadString(apiUri + tokenValue); if (o != null) { //凭证正确 Session["Token"] = o; //序列化用户的其它相关信息 Response.Write("恭喜,令牌存在,您被授权访问该页面!"); } else { //凭证错误 filterContext.Result = new RedirectResult(this.replaceToken()); } } else { //未持有令牌 filterContext.Result = new RedirectResult(this.replaceToken()); } } //未进行令牌验证,去主站验证 else { filterContext.Result = new RedirectResult(this.getTokenURL()); } } base.OnActionExecuting(filterContext); }
protected override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { if (LayoutImagesLoaded) { ViewBag.ShouldLoadLayoutImages = false; } else { ViewBag.ShouldLoadLayoutImages = true; LayoutImagesLoaded = true; } base.OnActionExecuting(filterContext); }
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { bool result = false; if (this.Permission == null || this.Permission.Length == 0) { result = true; } else { foreach (var r in Permission) { result = filterContext.RequestContext.RouteData.CheckRole(r); if (result) { break; } } } #region 处理判断结果 if (result) { base.OnActionExecuting(filterContext); } else { if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.Result = new JsonResult() { Data = new ReturnResult() { Status = 403, Message = "权限不足!" } }; } else { //if (filterContext.HttpContext.Request.UrlReferrer != null) // filterContext.Result = new RedirectResult(filterContext.HttpContext.Request.UrlReferrer.ToString()); //else // filterContext.Result = new RedirectResult("/"); filterContext.Result = new RedirectResult("/public/error?message=权限不足"); } } #endregion }
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext) { string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower(); HttpSessionStateBase session = filterContext.HttpContext.Session; if (session.IsNewSession) { //Redirect var url = new UrlHelper(filterContext.RequestContext); var loginUrl = url.Content("~/Home/Login"); filterContext.HttpContext.Response.Redirect(loginUrl, true); } }