コード例 #1
0
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     if (!context.RouteData.DataTokens.ContainsKey("actionName"))
     {
         context.RouteData.DataTokens.Add("actionName", context.ActionDescriptor.Name);
     }
 }
コード例 #2
0
        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;
        }
コード例 #5
0
 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 });
 }
コード例 #6
0
 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
ファイル: ValidateModel.cs プロジェクト: aguldstrand/Tasky
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     if (!context.ModelState.IsValid)
     {
         context.Result = new BadRequestObjectResult(context.ModelState);
     }
 }
コード例 #9
0
        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;
                }
            }
        }
コード例 #10
0
 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);
 }
コード例 #12
0
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     context.Result = new ContentResult
     {
         Content = "The Action was never executed",
         ContentType = new MediaTypeHeaderValue("text/plain")
     };
 }
コード例 #13
0
 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() } });
     }
 }
コード例 #16
0
 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;
        }
コード例 #18
0
 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);
         }
     }
 }
コード例 #19
0
            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
ファイル: BananaRequiredFilter.cs プロジェクト: rafsan/Cancel
        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);
             }
         }
     }
 }
コード例 #24
0
 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;
         }
     }
 }
コード例 #25
0
        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
ファイル: BasicAuth.cs プロジェクト: mbelles/web-api-401s
		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();
		}
コード例 #28
0
		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);
        }