예제 #1
0
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     if (!context.RouteData.DataTokens.ContainsKey("actionName"))
     {
         context.RouteData.DataTokens.Add("actionName", context.ActionDescriptor.Name);
     }
 }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var bodyParameter = context.ActionDescriptor
                                          .Parameters
                                          .FirstOrDefault(parameter => IsBodyBindingSource(
                                              parameter.BindingInfo?.BindingSource));
                if (bodyParameter != null)
                {
                    var parameterBindingErrors = context.ModelState[bodyParameter.Name].Errors;
                    if (parameterBindingErrors.Count != 0)
                    {
                        var errorInfo = new ErrorInfo
                        {
                            ActionName = context.ActionDescriptor.Name,
                            ParameterName = bodyParameter.Name,
                            Errors = parameterBindingErrors.Select(x => x.ErrorMessage).ToList(),
                            Source = "filter"
                        };

                        context.Result = new ObjectResult(errorInfo);
                    }
                }
            }

            base.OnActionExecuting(context);
        }
예제 #3
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (Mongo.IsConnected())
            {
                //Try to get current user
                try
                {
                    string id = Context.User.FindFirst(ClaimTypes.NameIdentifier).Value;
                    kUser user = Mongo.GetUserById(id);

                    //Likely a deleted user who still has claims
                    if (user == null)
                    {
                        Context.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
                        model.User = null;
                    }
                    else
                    {
                        model.User = user;
                    }
                }
                catch { model.User = null; }

                //Get themes
                List<string> themes = new List<string>();
                foreach (var theme in Mongo.GetEnabledThemes())
                {
                    string file = Url.Content("~/Style/Themes/" + theme + ".css");
                    themes.Add(file);
                }
                model.Themes = themes.ToArray();
            }

            base.OnActionExecuting(context);
        }
예제 #4
0
        public BreadcrumbModel CreateBreadcrumb(Controller currentController, ActionExecutingContext filterContext)
        {
            var result = new BreadcrumbModel();

            var controllerType = currentController.GetType();
            var actionName = filterContext.RouteData.Values["action"].ToString();

            var routeKey = GetRouteKey(controllerType, actionName);

            //Add the current route
            var currrentAction = GetItemByKey(routeKey);

            if (currrentAction == null)
                return result;

            result.Items.Add(BreadcrumbActionToMenuItem(currrentAction, filterContext.RouteData, true));

            while (currrentAction?.ParentKey.IsNotBlank() ?? false)
            {
                currrentAction = GetItemByKey(currrentAction.ParentKey);

                //TODO improve, there is no need to go to the next loop
                if (currrentAction == null)
                    continue;

                var ancestorMenuItem = BreadcrumbActionToMenuItem(currrentAction, filterContext.RouteData, false);

                result.Items.Insert(0, ancestorMenuItem);
            }

            return result;
        }
 public void OnActionExecuting(ActionExecutingContext context)
 {
     this.logger.Log(context.HttpContext.Request.Method + " " +
         context.HttpContext.Request.Path + " " +
         this.requestIdService.RequestId);
     context.HttpContext.Response.Headers.Add("request-id", new string[] { this.requestIdService.RequestId });
 }
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     var validator = new ASP5_RequestValidator();
     if (!validator.IsValidRequest(this.Context, Restricted.TWILIO_AUTH_TOKEN))
         throw new UnauthorizedAccessException("Twilio validation failed");
     base.OnActionExecuting(context);
 }
예제 #7
0
        public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            string[] jwtArray;
            context.HttpContext.Request.Headers.TryGetValue("Authorization", out jwtArray);
            if (jwtArray == null || !jwtArray.Any()) return Task.FromResult(context.Result = new HttpUnauthorizedResult());
            var jwt = jwtArray[0].Replace("Bearer ", string.Empty);

            try
            {
                var jsonPayload = JsonWebToken.Decode(jwt, JwtConstants.SecretKey);
                var user = JsonConvert.DeserializeObject<JwtPayload>(jsonPayload).Sub;
                //var user = new User() {Name = "Velkata", Roles = new[] {"Admin"}};
                context.HttpContext.User = new ProfilePrincipal(new GenericIdentity(user.Name), user.Id, user.Roles, user.Email, user.Picture);

                //check roles
                if (_roles != null)
                    if (!HasRolePermissions(user.Roles))
                        return Task.FromResult(context.Result = new HttpUnauthorizedResult());

                return base.OnActionExecutionAsync(context, next);
            }
            catch (SignatureVerificationException)
            {
                return Task.FromResult(context.Result = new HttpUnauthorizedResult());
            }
            catch (Exception ex)
            {
                return Task.FromResult(context.Result = new HttpStatusCodeResult(500));
            }
        }
예제 #8
0
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     if (!context.ModelState.IsValid)
     {
         context.Result = new BadRequestObjectResult(context.ModelState);
     }
 }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            object age = null;

            var controller = context.Controller as FiltersController;

            if (controller != null)
            {
                controller.CustomUser.Log += "Age Enhanced!" + Environment.NewLine;
            }

            if (context.ActionArguments.TryGetValue("age", out age))
            {
                if (age is int)
                {
                    var intAge = (int)age;

                    if (intAge < 21)
                    {
                        intAge += 5;
                    }
                    else if (intAge > 30)
                    {
                        intAge = 29;
                    }

                    context.ActionArguments["age"] = intAge;
                }
            }
        }
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     if (context.ActionDescriptor.DisplayName == "FiltersWebSite.ActionFilterController.GetHelloWorld")
     {
         (context.ActionArguments["fromGlobalActionFilter"] as List<ContentResult>).
             Add(Helpers.GetContentResult(context.Result, "Action Filter - OnActionExecuting"));
     }
 }
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     if (!string.IsNullOrEmpty(context.HttpContext.Request.Query["culture"]))
     {
         CultureInfo.DefaultThreadCurrentCulture = CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(context.HttpContext.Request.Query["culture"]);
     }
     base.OnActionExecuting(context);
 }
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     context.Result = new ContentResult
     {
         Content = "The Action was never executed",
         ContentType = new MediaTypeHeaderValue("text/plain")
     };
 }
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     context.Result = new ContentResult
     {
         Content = "The Action was never executed",
         ContentType = "text/plain"
     };
 }
예제 #14
0
        // Need suggestions on improvising the session settings
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if(User.Identity.IsAuthenticated && AppSession.AppUserId == null)
                SetAppSession();

            //Set any values if you have for all the action requests
            ActionStartup();
        }
예제 #15
0
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     var userName = context.HttpContext.Session.GetString("signin-user");
     if (string.IsNullOrEmpty(userName))
     {
         context.Result = new RedirectToActionResult(ActionName ?? "Login", ControllerName ?? "Account",
             new Dictionary<string, object> { { "ReturnUrl", context.HttpContext.Request.Path.ToUriComponent() } });
     }
 }
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     if (!context.ModelState.IsValid)
     {
         context.Result = new ObjectResult(context.ModelState)
         {
             StatusCode = StatusCodes.Status400BadRequest
         };
     }
 }
예제 #17
0
        /// <summary>
        /// check if request is authorized
        /// </summary>
        /// <param name="context"></param>
        /// <param name="roles"></param>
        /// <returns></returns>
        private bool IsAuthorized(ActionExecutingContext context, string[] roles)
        {
            var principal = context.HttpContext.User;

            if (principal == null)
                return false;

            var identity = principal.Identity as ErpIdentity;
            return identity != null;
        }
 public void OnActionExecuting(ActionExecutingContext context)
 {
     if (context.ActionArguments.Any())
     {
         var request = context.ActionArguments.FirstOrDefault(arg => arg.Value is Request);
         if (request.Value != null)
         {
             _workspace.BufferManager.UpdateBuffer((Request)request.Value);
         }
     }
 }
            public void OnActionExecuting(ActionExecutingContext context)
            {
                if (!context.ActionArguments.Any()) return;

                //put the model in the context, we'll resolve that after it's executed
                var file = context.ActionArguments.First().Value as RequestModel;
                if (file != null)
                {
                    context.HttpContext.Items[nameof(CheckNotModifiedAttribute)] = file;
                }
            }
예제 #20
0
        public void OnActionExecuting(ActionExecutingContext context)
        {
            object originalUserName = null;

            context.ActionArguments.TryGetValue("userName", out originalUserName);

            var userName = originalUserName as string;

            if (string.IsNullOrWhiteSpace(userName))
            {
                context.ActionArguments["userName"] = _nameService.GetName();
            }
        }
예제 #21
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if(!context.HttpContext.Request.Query.ContainsKey(_requiredKeyword))
            {
                context.Result = new ContentResult()
                {
                    StatusCode = 418,
                    Content = String.Format("Sorry, no {0} here", _requiredKeyword)
                };
            }

            base.OnActionExecuting(context);
        }
예제 #22
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.ActionDescriptor.DisplayName == "FiltersWebSite.ProductsController.GetPrice")
            {
                context.HttpContext.Response.Headers.Append("filters",
                    "On Controller Action Filter - OnActionExecuting");
            }

            if (context.ActionDescriptor.DisplayName == "FiltersWebSite.ActionFilterController.GetHelloWorld")
            {
                (context.ActionArguments["fromGlobalActionFilter"] as List<ContentResult>)
                    .Add(Helpers.GetContentResult(context.Result, "Controller Action filter - OnActionExecuting"));
            }
        }
예제 #23
0
 public void OnActionExecuting(ActionExecutingContext context)
 {
     if (context.ActionArguments.Any())
     {
         var request = context.ActionArguments.FirstOrDefault(arg => arg.Value is Request);
         if (request.Value != null)
         {
             var typedRequest = (Request)request.Value;
             if (typedRequest.Buffer != null && typedRequest.FileName != null)
             {
                 _workspace.EnsureBufferUpdated(typedRequest);
             }
         }
     }
 }
 public void OnActionExecuting(ActionExecutingContext context)
 {
     if (!context.ActionArguments.Any()) return;
     var file = context.ActionArguments.First().Value as RequestModel;
     if (file != null)
     {
         FileResult result;
         DateTime lastWrite;
         if (TryGetCachedCompositeFileResult(_fileSystemHelper, file.FileKey, file.Compression, file.Mime, out result, out lastWrite))
         {
             file.LastFileWriteTime = lastWrite;
             context.Result = result;
         }
     }
 }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var model = OperationResult.ErrorResult("错误的请求");
                var result = new ObjectResult(model);
                result.StatusCode = StatusCodes.Status400BadRequest;

                context.Result = result;
            }
            else
            {
                base.OnActionExecuting(context);
            }
        }
예제 #26
0
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (context.HttpContext.Request.Method == "GET")
            {
                // slow down incoming GET requests
                await Task.Delay(Delay);
            }

            var executedContext = await next();

            if (executedContext.Result is ViewResult)
            {
                // slow down outgoing view results
                await Task.Delay(Delay);
            }
        }
예제 #27
0
		public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
		{
			if (Authorize(context))
			{
				await next();
				return;
			}

			context.Result = new HttpUnauthorizedResult();
			
			var request = context.HttpContext.Request;
			var response = context.HttpContext.Response;
			var dnsSafeHost = "locahost";

			response.Headers.Add("WWW-Authenticate", new string[] { $"Basic realm={dnsSafeHost}" });
			response.Challenge();
		}
		public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
		{
			var actionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
			var actionAttribute = actionDescriptor?.MethodInfo.GetCustomAttribute<ActionRelationAttribute>(true);

			if (actionAttribute != null)
			{
				var problem = await actionAttribute.ExecuteSuitableValidationsAsync(context.HttpContext.RequestServices, context.ActionArguments);

				if (problem.HasValue)
				{
					throw new ApiException(problem.Value);
				}
			}

			await next();
		}
예제 #29
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            object obj;
            List<ContentResult> filters;

            if (context.ActionArguments.TryGetValue("fromGlobalActionFilter", out obj))
            {
                filters = (List<ContentResult>)obj;
            }
            else
            {
                filters = new List<ContentResult>();
                context.ActionArguments.Add("fromGlobalActionFilter", filters);
            }

            filters.Add(Helpers.GetContentResult(context.Result, "Controller override - OnActionExecuting"));
        }
예제 #30
0
        public override void OnActionExecuting(ActionExecutingContext actionExecutingContext)
        {
            if (!actionExecutingContext.HttpContext.User.Identity.IsAuthenticated)
              {
            string actionName = actionExecutingContext.ActionDescriptor.Name.ToLower();
            string controllerName = (actionExecutingContext.ActionDescriptor as ControllerActionDescriptor).ControllerName.ToLower();

            if (!((actionName == "signin" || actionName == "restorepassword") && controllerName == "account"))
            {
              actionExecutingContext.Result = new RedirectResult("/backend/account/signin");
              return;
            }
              }

              this.HandleViewModelMultilingualProperties(actionExecutingContext);
              base.OnActionExecuting(actionExecutingContext);
        }