コード例 #1
1
        // This is used as a 'common' test method for ActionFilterAttribute and Controller
        public static async Task ActionFilter_SettingResult_ShortCircuits(Mock mock)
        {
            // Arrange
            mock.As<IAsyncActionFilter>()
                .Setup(f => f.OnActionExecutionAsync(
                    It.IsAny<ActionExecutingContext>(),
                    It.IsAny<ActionExecutionDelegate>()))
                .CallBase();

            mock.As<IActionFilter>()
                .Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>()))
                .Callback<ActionExecutingContext>(c =>
                {
                    mock.ToString();
                    c.Result = new NoOpResult();
                });

            mock.As<IActionFilter>()
                .Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
                .Verifiable();

            var context = CreateActionExecutingContext(mock.As<IFilter>().Object);
            var next = new ActionExecutionDelegate(() => { throw null; }); // This won't run

            // Act
            await mock.As<IAsyncActionFilter>().Object.OnActionExecutionAsync(context, next);

            // Assert
            Assert.IsType<NoOpResult>(context.Result);

            mock.As<IActionFilter>()
                .Verify(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()), Times.Never());
        }
コード例 #2
0
 public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
 {
     if (context.HttpContext.Request.Method == "GET")
     {
         await HandleQueryRequest(context, next);
     }
 }
コード例 #3
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            using (AbpCrossCuttingConcerns.Applying(context.Controller, AbpCrossCuttingConcerns.Auditing))
            {
                if (!ShouldSaveAudit(context))
                {
                    await next();
                    return;
                }

                var auditInfo = CreateAuditInfo(context);
                var stopwatch = Stopwatch.StartNew();

                try
                {
                    var result = await next();
                    if (result.Exception != null && !result.ExceptionHandled)
                    {
                        auditInfo.Exception = result.Exception;
                    }
                }
                catch (Exception ex)
                {
                    auditInfo.Exception = ex;
                    throw;
                }
                finally
                {
                    stopwatch.Stop();
                    auditInfo.ExecutionDuration = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds);
                    AuditInfoProvider?.Fill(auditInfo);
                    await AuditingStore.SaveAsync(auditInfo);
                }
            }
        }
コード例 #4
0
        // This is used as a 'common' test method for ActionFilterAttribute and Controller
        public static async Task ActionFilter_Calls_OnActionExecuted(Mock mock)
        {
            // Arrange
            mock.As<IAsyncActionFilter>()
                .Setup(f => f.OnActionExecutionAsync(
                    It.IsAny<ActionExecutingContext>(),
                    It.IsAny<ActionExecutionDelegate>()))
                .CallBase();

            mock.As<IActionFilter>()
                .Setup(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>()))
                .Verifiable();

            mock.As<IActionFilter>()
                .Setup(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()))
                .Verifiable();

            var context = CreateActionExecutingContext(mock.As<IFilter>().Object);
            var next = new ActionExecutionDelegate(() => Task.FromResult(CreateActionExecutedContext(context)));

            // Act
            await mock.As<IAsyncActionFilter>().Object.OnActionExecutionAsync(context, next);

            // Assert
            Assert.Null(context.Result);

            mock.As<IActionFilter>()
                .Verify(f => f.OnActionExecuting(It.IsAny<ActionExecutingContext>()), Times.Once());

            mock.As<IActionFilter>()
                .Verify(f => f.OnActionExecuted(It.IsAny<ActionExecutedContext>()), Times.Once());
        }
コード例 #5
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (!ShouldSaveAudit(context))
            {
                await next();
                return;
            }

            var auditInfo = CreateAuditInfo(context);
            var stopwatch = Stopwatch.StartNew();

            try
            {
                await next();
            }
            catch (Exception ex)
            {
                auditInfo.Exception = ex;
                throw;
            }
            finally
            {
                stopwatch.Stop();
                auditInfo.ExecutionDuration = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds);
                AuditInfoProvider?.Fill(auditInfo);
                await AuditingStore.SaveAsync(auditInfo);
            }
        }
コード例 #6
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));
            }
        }
コード例 #7
0
 public async Task OnActionExecutionAsync(ActionExecutingContext context, 
     ActionExecutionDelegate next)
 {
     // do something before the action executes
     await next();
     // do something after the action executes
 }
コード例 #8
0
		public override async Task OnActionExecutionAsync(ActionExecutingContext startContext, ActionExecutionDelegate next)
		{
			_stopwatch = Stopwatch.StartNew();

			var endContext = await next();

			Debug.WriteLine($"Action ended in {_stopwatch.Elapsed}");
		}
コード例 #9
0
ファイル: BaseController.cs プロジェクト: Jeffiy/vnextcn.org
 public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
 {
     if (context.HttpContext.Request.Headers["private-key"].ToString() != Configuration["PrivateKey"].ToString())
     {
         context.Result = new ChallengeResult();
         return Task.FromResult(403);
     }
     return base.OnActionExecutionAsync(context, next);
 }
コード例 #10
0
ファイル: ApiController.cs プロジェクト: Jeffiy/vnextcn.org
 public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
 {
     var pk = context.HttpContext.Request.Headers["PrivateKey"].ToString();
     if (DB.Nodes.Where(x => x.PrivateKey == pk).Count() == 0)
     {
         context.Result = new ChallengeResult();
         return Task.FromResult(403);
     }
     return base.OnActionExecutionAsync(context, next);
 }
コード例 #11
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            using (AbpCrossCuttingConcerns.Applying(context.Controller, AbpCrossCuttingConcerns.Validation))
            {
                using (var validator = _iocResolver.ResolveAsDisposable<MvcActionInvocationValidator>())
                {
                    validator.Object.Initialize(context);
                    validator.Object.Validate();
                }

                await next();
            }
        }
コード例 #12
0
ファイル: AdminFilter.cs プロジェクト: jchenga/Orchard2
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (AdminAttribute.IsApplied(context.HttpContext) || IsNameAdmin(context))
            {
                var authorized = await _authorizationService.AuthorizeAsync(context.HttpContext.User, Permissions.AccessAdminPanel);

                if (!authorized)
                {
                    context.Result = new UnauthorizedResult();
                    return;
                }
            }

            await base.OnActionExecutionAsync(context, next);
        }
コード例 #13
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);
            }
        }
コード例 #14
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();
		}
コード例 #15
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();
		}
コード例 #16
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var unitOfWorkAttr = UnitOfWorkAttribute
                .GetUnitOfWorkAttributeOrNull(context.ActionDescriptor.GetMethodInfo()) ??
                new UnitOfWorkAttribute(); //TODO: GetUnitOfWorkAttributeOrNull also checks for conventional classes, which makes this duplicate

            if (unitOfWorkAttr.IsDisabled)
            {
                await next();
                return;
            }

            using (var uow = _unitOfWorkManager.Begin(unitOfWorkAttr.CreateOptions()))
            {
                await next();
                await uow.CompleteAsync();
            }
        }
コード例 #17
0
        public virtual async Task OnActionExecutionAsync(
            ActionExecutingContext context,
            ActionExecutionDelegate next)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            OnActionExecuting(context);
            if (context.Result == null)
            {
                OnActionExecuted(await next());
            }
        }
コード例 #18
0
        /// <inheritdoc />
        public async Task OnActionExecutionAsync(
            ActionExecutingContext context,
            ActionExecutionDelegate next)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            var controller = context.Controller;
            if (controller == null)
            {
                throw new InvalidOperationException(Resources.FormatPropertyOfTypeCannotBeNull(
                    nameof(context.Controller),
                    nameof(ActionExecutingContext)));
            }

            IAsyncActionFilter asyncActionFilter;
            IActionFilter actionFilter;
            if ((asyncActionFilter = controller as IAsyncActionFilter) != null)
            {
                await asyncActionFilter.OnActionExecutionAsync(context, next);
            }
            else if ((actionFilter = controller as IActionFilter) != null)
            {
                actionFilter.OnActionExecuting(context);
                if (context.Result == null)
                {
                    actionFilter.OnActionExecuted(await next());
                }
            }
            else
            {
                await next();
            }
        }
コード例 #19
0
		/// <summary>
		/// Ensures the user is signed in if being signed in is required.
		/// </summary>
		public async Task OnActionExecutionAsync(
			ActionExecutingContext context, 
			ActionExecutionDelegate next)
		{
			var baseController = context.Controller as BaseController;
			if (baseController == null)
			{
				throw new InvalidOperationException(
					"Controller must inherit from BaseController.");
			}
			
			if (AccessRequired >= RequiredAccess.Authenticated 
				&& baseController.IdentityState == IdentityState.Anonymous)
			{
				context.Result = baseController.RedirectToSignIn();
				return;
			}

			if (AccessRequired >= RequiredAccess.Registered 
				&& baseController.IdentityState == IdentityState.Unregistered)
			{
				context.Result = baseController.Forbid();
				return;
			}
			
			if (AccessRequired >= RequiredAccess.SuperUser 
				&& baseController.IdentityState != IdentityState.SuperUser)
			{
				context.Result = baseController.Forbid();
				return;
			}

			if (baseController.IdentityState != IdentityState.SuperUser 
				&& !IsAuthorized(baseController))
			{
				context.Result = baseController.Forbid();
				return;
			}

			await next();
		}
コード例 #20
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var unitOfWorkAttr = UnitOfWorkAttribute
                .GetUnitOfWorkAttributeOrNull(context.ActionDescriptor.GetMethodInfo()) ??
                _configuration.DefaultUnitOfWorkAttribute;

            if (unitOfWorkAttr.IsDisabled)
            {
                await next();
                return;
            }

            using (var uow = _unitOfWorkManager.Begin(unitOfWorkAttr.CreateOptions()))
            {
                var result = await next();
                if (result.Exception == null || result.ExceptionHandled)
                {
                    await uow.CompleteAsync();
                }
            }
        }
コード例 #21
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (!ShouldSaveAudit(context))
            {
                await next();
                return;
            }

            using (AbpCrossCuttingConcerns.Applying(context.Controller, AbpCrossCuttingConcerns.Auditing))
            {
                var auditInfo = _auditingHelper.CreateAuditInfo(
                    context.ActionDescriptor.AsControllerActionDescriptor().MethodInfo,
                    context.ActionArguments
                );

                var stopwatch = Stopwatch.StartNew();

                try
                {
                    var result = await next();
                    if (result.Exception != null && !result.ExceptionHandled)
                    {
                        auditInfo.Exception = result.Exception;
                    }
                }
                catch (Exception ex)
                {
                    auditInfo.Exception = ex;
                    throw;
                }
                finally
                {
                    stopwatch.Stop();
                    auditInfo.ExecutionDuration = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds);
                    await _auditingHelper.SaveAsync(auditInfo);
                }
            }
        }
コード例 #22
0
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (!context.ModelState.IsValid)
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;

                var errors = new JObject();
                foreach (var key in context.ModelState.Keys)
                {
                    var state = context.ModelState[key];
                    if (state.Errors.Count > 0)
                    {
                        errors[key] = state.Errors[0].ErrorMessage;
                    }
                }

                context.Result = new ObjectResult(errors);
            }
            else
            { 
                await next();
            }
        }
コード例 #23
0
ファイル: ApiController.cs プロジェクト: thecorrado/Warden
        //Improve performance e.g. by storing API keys in cache
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var apiKeyHeader = context.HttpContext.Request.Headers.FirstOrDefault(x => x.Key == "X-Api-Key");
            if (apiKeyHeader.Key.Empty())
            {
                context.HttpContext.Response.StatusCode = 401;
                return;
            }
            var apiKey = await ApiKeyService.GetAsync(apiKeyHeader.Value);
            if (apiKey == null)
            {
                context.HttpContext.Response.StatusCode = 401;
                return;
            }
            var isActive = await UserService.IsActiveAsync(apiKey.UserId);
            if (!isActive)
            {
                context.HttpContext.Response.StatusCode = 401;
                return;
            }

            UserId = apiKey.UserId;
            await next();
        }
コード例 #24
0
		/// <summary>
		/// Runs before the action is executing.
		/// </summary>
		public override async Task OnActionExecutionAsync(
			ActionExecutingContext context,
			ActionExecutionDelegate next)
		{
			if (!context.Filters.OfType<AuthorizationAttribute>().Any())
			{
				throw new InvalidOperationException(
					"All controllers/actions must have an authorization filter.");
			}

			if (!await _userProvider.IsServiceActivatedAsync())
			{
				context.Result = RedirectToAction("ActivateService", "Activation");
				return;
			}

			await InitializeAsync();

			if (!DoesResourceExist())
			{
				context.Result = NotFound();
				return;
			}

			await next();
		}
コード例 #25
0
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (commentsFeedNotificationTransport == null)
            {
                commentsFeedNotificationTransport = await feedRepo.GetCommentsFeedNotificationTransport();
            }

            var userId = User.GetUserId();
            await feedRepo.AddFeedNotificationTransportIfNeeded(userId);

            await next();
        }
コード例 #26
0
        /// <summary>
        /// Performs controller action pre-procesing to ensure that at least one of the specified features are enabled.
        /// </summary>
        /// <param name="context">The context of the MVC action.</param>
        /// <param name="next">The action delegate.</param>
        /// <returns>Returns a task representing the action execution unit of work.</returns>
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            IFeatureManagerSnapshot fm = context.HttpContext.RequestServices.GetRequiredService <IFeatureManagerSnapshot>();

            //
            // Enabled state is determined by either 'any' or 'all' features being enabled.
            bool enabled = RequirementType == RequirementType.All ?
                           Features.All(feature => fm.IsEnabled(feature)) :
                           Features.Any(feature => fm.IsEnabled(feature));

            if (enabled)
            {
                await next();
            }
            else
            {
                IDisabledFeaturesHandler disabledFeaturesHandler = context.HttpContext.RequestServices.GetService <IDisabledFeaturesHandler>() ?? new NotFoundDisabledFeaturesHandler();

                await disabledFeaturesHandler.HandleDisabledFeatures(Features, context);
            }
        }
コード例 #27
0
        public async Task OnActionExecutionAsync(ActionExecutingContext filterContext, ActionExecutionDelegate next)
        {
            KorisnickiNalog k = filterContext.HttpContext.GetLogiraniKorisnik();

            if (k == null)
            {
                if (filterContext.Controller is Controller controller)
                {
                    controller.TempData["error_poruka"] = "Niste logirani";
                }

                filterContext.Result = new RedirectToActionResult("Index", "Autentifikacija", new { @area = "" });
                return;
            }

            //Preuzimamo DbContext preko app services
            MyContext db = filterContext.HttpContext.RequestServices.GetService<MyContext>();

            //ucenici mogu pristupiti studenti
            if (_ucenik && db.Ucenik.Any(s => s.KorisnickiNalogId == k.Id))
            {
                await next(); //ok - ima pravo pristupa
                return;
            }

            //nastavnici mogu pristupiti studenti
            if (_nastavnici && db.Nastavnik.Any(s => s.KorisnickiNalogId == k.Id))
            {
                await next();//ok - ima pravo pristupa
                return;
            }

            if (filterContext.Controller is Controller c1)
            {
                c1.ViewData["error_poruka"] = "Nemate pravo pristupa";
            }
            filterContext.Result = new RedirectToActionResult("Index", "Home", new { @area = "" });
        }
 public async Task OnActionExecutionAsync(ActionExecutingContext context,
                                          ActionExecutionDelegate next)
 {
     context.HttpContext.Response.Headers.Add(header, value);
     await next().ConfigureAwait(false);
 }
コード例 #29
0
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            await this.store.Initialize();

            await base.OnActionExecutionAsync(context, next);
        }
コード例 #30
0
        public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            int id = (int)context.ActionArguments.Values.FirstOrDefault();

            var product = await _productService.GetByIdAsync(id);

            if (product != null)
            {
                await next();
            }
            else
            {
                ErrorDto errorDto = new ErrorDto();
                errorDto.Status = 404;
                errorDto.Errors.Add($"id'si {id} olan ürün veritabanında bulunamadı");

                context.Result = new NotFoundObjectResult(errorDto);
            }
        }
コード例 #31
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            IServiceProvider serviceProvider = context.HttpContext.RequestServices;
            var responseCacheOption          = serviceProvider.GetService <ResponseCacheOption>();

            //配置存在且配置关闭或者持续时长等于0,即忽略响应缓存
            if ((responseCacheOption != null && !responseCacheOption.Enabled) || Duration == 0)
            {
                goto gotoNext;
            }
            context.HttpContext.Request.EnableBuffering();
            var           _logger        = serviceProvider.GetRequiredService <ILogger <PostResponseCacheAttribute> >();
            var           _configuration = serviceProvider.GetRequiredService <IConfiguration>();
            var           _memorycache   = serviceProvider.GetService <IMemoryCache>();
            IRedisManager _redisManager  = null;

            if ((responseCacheOption != null && responseCacheOption.Cluster) || Cluster)
            {
                _redisManager = serviceProvider.GetService <IRedisManager>();
                if (_redisManager == null)
                {
                    throw new ArgumentNullException(nameof(IMemoryCache), "Post响应已启用集群模式,缓存依赖IRedisManager,请services.AddRedisManager()注入IRedisManager后再使用[PostResponseCache]");
                }
            }
            if (_memorycache == null)
            {
                throw new ArgumentNullException(nameof(IMemoryCache), "Post响应缓存依赖IMemoryCache,请services.AddMemoryCache()注入IMemoryCache后再使用[PostResponseCache]");
            }
            //标识已触发过响应缓存,防止中间件再次触发
            _memorycache.Set($"PostResponseCache_{context.HttpContext.Request.Path}", "标识已触发过响应缓存,防止中间件再次触发", new MemoryCacheEntryOptions {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
            });

            var _requestCacheData = serviceProvider.GetService <RequestCacheData>();

            if (_requestCacheData == null)
            {
                throw new ArgumentNullException(nameof(IMemoryCache), "Post响应缓存依赖ResponseCacheData,请调用services.AddShareRequestBody()注入后再使用[PostResponseCache]");
            }

            var token = context.HttpContext.RequestAborted.Register(async() =>
            {
                await Task.CompletedTask;
                return;
            });

            var descriptor = (Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor;

            var attribute = (IgnorePostResponseCacheAttribute)descriptor.MethodInfo.GetCustomAttributes(typeof(IgnorePostResponseCacheAttribute), true).FirstOrDefault();

            if (attribute != null)
            {
                //记录忽略的路由,中间件跳过
                _memorycache.Set($"IgnorePostResponseCache_{context.HttpContext.Request.Path}", true, new MemoryCacheEntryOptions {
                    AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
                });
                goto gotoNext;
            }

            if (context.HttpContext.Request.Method.Equals("get", StringComparison.OrdinalIgnoreCase) || context.HttpContext.Request.Method.Equals("head", StringComparison.OrdinalIgnoreCase))
            {
                goto gotoNext;
            }
            else
            {
                var convertedDictionatry = context.HttpContext.Request.Query.ToDictionary(s => s.Key.ToLower(), s => s.Value);

                foreach (var item in IgnoreVaryByQueryKeys ?? new string[0])
                {
                    if (convertedDictionatry.ContainsKey(item.ToLower()))
                    {
                        convertedDictionatry.Remove(item.ToLower());
                    }
                }

                StringBuilder requestStrKey = new StringBuilder(context.HttpContext.Request.Path);
                foreach (var item in convertedDictionatry)
                {
                    requestStrKey.Append($"{item.Key}{item.Value}");
                }

                string bodyValue;
                if (_requestCacheData == null || string.IsNullOrEmpty(_requestCacheData.Body))
                {
                    bodyValue = await Common.ReadAsString(context.HttpContext);

                    _requestCacheData = new RequestCacheData {
                        Body = bodyValue
                    };
                }
                else
                {
                    bodyValue = _requestCacheData.Body;
                }
                if (!string.IsNullOrEmpty(bodyValue) && !"null".Equals(bodyValue))
                {
                    //非Get请求body有值才被缓存,其他默认不缓存,防止body读取失败导致缓存异常
                    bodyValue = Regex.Replace(bodyValue, @"\s(?=([^""]*""[^""]*"")*[^""]*$)", string.Empty);
                    bodyValue = bodyValue.Replace("\r\n", "").Replace(" : ", ":").Replace("\n  ", "").Replace("\n", "").Replace(": ", ":").Replace(", ", ",");

                    requestStrKey.Append($"body{bodyValue}");
                    ResponseCacheData cacheResponseBody = null;
                    if (Cluster)
                    {
                        cacheResponseBody = _redisManager.Get <ResponseCacheData>($"NetProPostResponse:{requestStrKey}");
                    }
                    else
                    {
                        cacheResponseBody = _memorycache.Get <ResponseCacheData>($"NetProPostResponse:{requestStrKey}");
                    }

                    if (cacheResponseBody != null && !context.HttpContext.RequestAborted.IsCancellationRequested)
                    {
                        if (!context.HttpContext.Response.HasStarted)
                        {
                            _logger.LogInformation($"触发PostResponseCacheAttribute本地缓存");
                            switch (ResponseMode)
                            {
                            case ResponseMode.Cache:
                                context.HttpContext.Response.StatusCode  = cacheResponseBody.StatusCode;
                                context.HttpContext.Response.ContentType = cacheResponseBody.ContentType;
                                await context.HttpContext.Response.WriteAsync(cacheResponseBody.Body);

                                await Task.CompletedTask;
                                return;;

                            case ResponseMode.Error:
                                if (cacheResponseBody.StatusCode == 200)
                                {
                                    //TODO确定StatusCode与Headers响应的先后顺序
                                    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
                                    context.HttpContext.Response.Headers.Add("Kestrel-ResponseMode", $"{ResponseMode}");
                                    context.HttpContext.Response.ContentType = cacheResponseBody.ContentType;
                                    await context.HttpContext.Response.WriteAsync(JsonSerializer.Serialize(new
                                    {
                                        Code = -1,
                                        Msg  = $"{Message}"
                                    }, new JsonSerializerOptions
                                    {
                                        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                                        Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(System.Text.Unicode.UnicodeRanges.All)
                                    }), Encoding.UTF8);

                                    await Task.CompletedTask;
                                    return;
                                }
                                else
                                {
                                    context.HttpContext.Response.StatusCode  = cacheResponseBody.StatusCode;
                                    context.HttpContext.Response.ContentType = cacheResponseBody.ContentType;
                                    await context.HttpContext.Response.WriteAsync(cacheResponseBody.Body);

                                    await Task.CompletedTask;
                                    return;;
                                }
                            }
                        }
                        else
                        {
                            _logger.LogError($"StatusCode无法设置,因为响应已经启动,位置为:触发本地缓存开始赋值[responsecache2]");
                            await Task.CompletedTask;
                            return;
                        }
                    }
                    else if (!context.HttpContext.RequestAborted.IsCancellationRequested)
                    {
                        try
                        {
                            var actionResult = await next();

                            dynamic responseResult = (dynamic)actionResult.Result;
                            if (actionResult.Exception != null)
                            {
                                // 过滤器中await next();执行的始终是Action而不是下一个过滤器或者中间件
                                await Task.CompletedTask;
                                return;
                            }
                            if (responseResult == null)
                            {
                                await Task.CompletedTask;
                                return;
                            }
                            string body;
                            if (responseResult.GetType().Name == "EmptyResult")
                            {
                                await Task.CompletedTask;
                                return;
                            }
                            body = JsonSerializer.Serialize(responseResult.Value, new JsonSerializerOptions
                            {
                                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.Create(System.Text.Unicode.UnicodeRanges.All)
                            });
                            if (Cluster)
                            {
                                _redisManager.Set($"NetProPostResponse:{requestStrKey}", new ResponseCacheData
                                {
                                    Body        = body,
                                    ContentType = "application/json",
                                    StatusCode  = responseResult.StatusCode ?? 200,
                                }, TimeSpan.FromSeconds(Duration));
                            }
                            else
                            {
                                _memorycache.Set($"NetProPostResponse:{requestStrKey}", new ResponseCacheData
                                {
                                    Body        = body,
                                    ContentType = "application/json",
                                    StatusCode  = responseResult.StatusCode ?? 200,
                                }, TimeSpan.FromSeconds(Duration));
                            }
                        }
                        catch (Exception ex)
                        {
                            await Task.CompletedTask;
                            return;
                        }
                        await Task.CompletedTask;
                        return;
                    }
                    else if (context.HttpContext.RequestAborted.IsCancellationRequested)
                    {
                        await Task.CompletedTask;
                        return;
                    }
                }
                else if (!context.HttpContext.RequestAborted.IsCancellationRequested)
                {
                    goto gotoNext;
                }
                else
                {
                    await Task.CompletedTask;
                    return;
                }
            }

gotoNext:
            await next();
        }
コード例 #32
0
 public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
 {
     if (!UpdateManager.IsLoaded)
     {
         await UpdateManager.Load();
     }
     await base.OnActionExecutionAsync(context, next);
 }
コード例 #33
0
        public override async Task OnActionExecutionAsync(ActionExecutingContext actionContext, ActionExecutionDelegate next)
        {
            var isAuth = await CheckAuthorization(actionContext);

            if (!isAuth)
            {
                actionContext.Result = new ContentResult
                {
                    Content     = "Forbidden",
                    ContentType = "application/json; charset=utf-8",
                    StatusCode  = StatusCodes.Status403Forbidden
                };
            }

            await base.OnActionExecutionAsync(actionContext, next);
        }
コード例 #34
0
        //private readonly IUnitOfWorkManager unitOfWorkManager;

        //public UnitOfWorkFilterAttribute(IUnitOfWorkManager unitOfWorkManager)
        //{
        //    this.unitOfWorkManager = unitOfWorkManager;
        //}

        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var uowInstance = context.HttpContext.RequestServices.GetRequiredService <IUnitOfWorkManager>();

            using var uow = await uowInstance.Reserve();

            //using var uow = await unitOfWorkManager.Reserve();
            await next.Invoke();

            await uow.CommitAsync();
        }
コード例 #35
0
        public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            int id       = (int)context.ActionArguments.Values.FirstOrDefault();
            var category = await _categoryApiService.GetByIdAsync(id);

            if (category != null)
            {
                await next();
            }
            else
            {
                ErrorDto errorDto = new ErrorDto();

                errorDto.Errors.Add($"id si {id} olan kategori veritabında bulunamadı.");
                context.Result = new RedirectToActionResult("Error", "Home", errorDto);
            }
        }
コード例 #36
0
ファイル: BaseController.cs プロジェクト: applenele/CSTAMS
 public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
 {
     return base.OnActionExecutionAsync(context, next);
 }
コード例 #37
0
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (_zipkinManager == null)
            {
                throw new ArgumentException("Инициализируй ZIPKIN MANAGER!!!");
            }

            var controllerActionDescriptor = (ControllerActionDescriptor)context.ActionDescriptor;
            var actionName     = $"{context.HttpContext.Request.Method}:{controllerActionDescriptor.AttributeRouteInfo.Template}";
            var controllerName = controllerActionDescriptor.ControllerName + "Controller";

            if (string.IsNullOrEmpty(_metricEntity))
            {
                _metricEntity = controllerActionDescriptor.ControllerName;
            }

            var metricsFactory =
                ControllerNameMetricsFactories.GetOrAdd(
                    controllerName,
                    MetricsTracingFactory.CreateControllerMetricsFactory(controllerName, _longRequestTime, "client_header_name"));

            var serviceName = "Unknown";
            var clientName  = "Unknown";


            if (context.HttpContext.Items.TryGetValue(CommonBehavior.ServiceNameItemKey, out var serviceNameValue))
            {
                serviceName = serviceNameValue as string;
            }

            if (context.HttpContext.Items.TryGetValue(CommonBehavior.ClientNameItemKey, out var clientNameValue))
            {
                clientName = clientNameValue as string;
            }

            //HttpContext.Items.ContainsKey(ServiceNameKey) ? httpContext.Items[ServiceNameKey].ToString() : string.Empty
            using (TryGetTrace(context.HttpContext, out var trace)

                ? _longRequestLoggingEnabled
                    ? metricsFactory.CreateTracingWithLoggingMetricsTimerOnExistingTrace(trace, _metricEntity, actionName, context.ActionArguments, serviceName, clientName)
                    : metricsFactory.CreateTracingMetricsTimerOnExistingTrace(trace, _metricEntity, actionName, serviceName, clientName)

                : _longRequestLoggingEnabled
                    ? metricsFactory.CreateLoggingMetricsTimer(_metricEntity, actionName, context.ActionArguments, serviceName, clientName)
                    : metricsFactory.CreateMetricsTimer(_metricEntity, actionName, serviceName, clientName))
            {
                await next.Invoke();
            }
        }
コード例 #38
0
 public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
 {
     return(base.OnActionExecutionAsync(context, next));
 }
コード例 #39
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);
            }
        }
コード例 #40
0
 private async Task HandleQueryRequest(ActionExecutingContext context, ActionExecutionDelegate next)
 {
     var url = context.Controller.GetType() + "|" + context.ActionDescriptor.DisplayName;
     _logger.LogWarning($"GET request recieved ({url}), checking cache...");
     
     var resp = await _store.Get(url);
     if (resp == null)
         await next();
     else
     {
         context.Result = new JsonResult(JsonConvert.DeserializeObject(resp));
         _logger.LogWarning($"Found cache entry {url} returning");
     }
 }
コード例 #41
0
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (!context.ModelState.IsValid)
            {
                var error = context.ModelState
                            .FirstOrDefault(x => x.Value.Errors.Any())
                            .Value
                            .Errors.FirstOrDefault();

                context.Result = new BadRequestObjectResult(
                    new ApiErrorResult
                {
                    Success      = false,
                    ErrorCode    = ApiErrorCodes.InvalidParamters.ToString(),
                    ErrorMessage = error?.ErrorMessage != null && error.ErrorMessage.IsNullOrEmpty() ? error.Exception.Message : error?.ErrorMessage,
                });

                return;
            }

            await next();
        }
コード例 #42
0
 public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
 {
     if (context.HttpContext.Session.GetString("Admin") != "true")
         context.Result = new RedirectResult("/Admin/Login");
     return base.OnActionExecutionAsync(context, next);
 }
コード例 #43
0
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            Guard.ThrownExceptionIfNull(context, nameof(context));

            if (context.ActionArguments.TryGetValue("q", out object searchValue))
            {
                // Showing searched posts
                Instance.PagedPosts = await _postService.FindPublishedForPaginationOrderByDateDescending(searchValue.ToString());
            }
            else
            {
                if (context.ActionArguments.TryGetValue("page", out object value) && int.TryParse(value.ToString(), out int page))
                {
                    // Showing posts after paging
                    Instance.PagedPosts = await _postService.GetPublishedForPagination(page);
                }
                else
                {
                    // Showing regular posts
                    Instance.PagedPosts = await _postService.GetPublishedForPagination();
                }
            }

            Instance.LatestPosts = await _postService.GetPublishedLatestPosts(3);

            Instance.Pages = await _pageService.GetAllPublished();

            Instance.Categories = await _categoryService.GetCategoriesWithPostCount();

            Instance.CategoriesWithPosts = await _categoryService.GetCategoriesWithPost();

            Instance.Tags = await _tagService.GetAllTags();


            await base.OnActionExecutionAsync(context, next);
        }
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if(context.HttpContext.Request.Method != HttpMethod.Post.ToString())
            {
                throw new reCAPTCHAException("ValidateRecaptchaAttribute must only decorate POST actions.");
            }

            StringValues recaptchaResponse;
            try {
                recaptchaResponse = context.HttpContext.Request.Form["g-recaptcha-response"];
            }
            catch(InvalidOperationException exc)
            {
                throw new reCAPTCHAException("reCAPTCHA failure, likely due to ValidateRecaptchaAttribute improperly decorating an action to which an unintended request has been posted.", exc);
            }

            if (String.IsNullOrWhiteSpace(recaptchaResponse))
            {
                context.ModelState.AddModelError("reCAPTCHAFailure", ErrorMessage);
                await next();
            }

            var builder = new ConfigurationBuilder();
            builder.AddJsonFile("appsettings.json");
            builder.AddEnvironmentVariables();
            var config = builder.Build();
            var siteSecret = config["RecaptchaOptions:Secret"];

            if (String.IsNullOrWhiteSpace(siteSecret))
            {
                throw new reCAPTCHAException("Could not find value for reCAPTCHA Secret in appsettings.json.");
            }

            using (var client = new HttpClient())
            {
                var values = new Dictionary<string, string>
                {
                   { "secret", siteSecret },
                   { "response", context.HttpContext.Request.Form["g-recaptcha-response"] },
                   { "remoteip", GetRemoteIp(context) }
                };
                var content = new FormUrlEncodedContent(values);

                HttpResponseMessage response;
                try {
                    response = await client.PostAsync(verificationUrl, content);
                }
                catch(HttpRequestException exc)
                {
                    throw new reCAPTCHAException("Could not reach Google's reCAPTCHA service for verification.", exc);
                }
                var responseString = await response.Content.ReadAsStringAsync();

                var converter = new ExpandoObjectConverter();
                try {
                    dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(responseString, converter);
                    bool isHuman = obj.success;

                    if (!isHuman)
                    {
                        context.ModelState.AddModelError("reCAPTCHAFailure", ErrorMessage);
                    }
                }
                catch(RuntimeBinderException exc)
                {
                    throw new reCAPTCHAException("Response from Google's verification service was in an unexpected format:" + responseString, exc);
                }
            }

            await next();
        }
コード例 #45
0
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (Configuration.AuditDisabled || IsActionIgnored(context.ActionDescriptor))
            {
                await next.Invoke();

                return;
            }
            await BeforeExecutingAsync(context);

            var actionExecutedContext = await next.Invoke();

            await AfterExecutedAsync(actionExecutedContext);
        }
 public abstract Task OnActionWithInvalidModelStateExecutionAsync(ActionExecutingContext context,
                                                                  ActionExecutionDelegate next);
コード例 #47
0
 public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
 {
     await this.store.Initialize();
     await base.OnActionExecutionAsync(context, next);
 }
コード例 #48
0
        //2-Methods: (Interface Implementation)
        //implement the interface by implementing its method below:
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            //check the Role of the user if it matches any of the allowed specified Roles.
            //split the above Roles string to an array of roles.
            //check this array if the user's role matches any of its element.
            //once there is a match, assign isRoleBasedAuthorized=true and break the foreach loop.
            //because we need to prove that user's role matches only one of the roles array elements.
            //But first, check Roles if it is not empty,
            //if it is not empty, that means we passed a value to Roles when we used this Attribute in a method (e.g: [CustomeAuthorizeForAjaxAndNonAjax(Roles ="SuperAdmin, Admin")] ) so process it.
            //if it is empty, that means we used this attribute without specifying Roles [CustomeAuthorizeForAjaxAndNonAjax], so consider the user is isRoleBasedAuthorized = true in the subsequesnt processing.
            bool isRoleBasedAuthorized = false;

            if (!string.IsNullOrEmpty(Roles))
            {
                string[] roles = Roles.Split(',');
                foreach (var role in roles)
                {
                    if (context.HttpContext.User.IsInRole(role))
                    {
                        isRoleBasedAuthorized = true;
                        break;
                    }
                    else
                    {
                        isRoleBasedAuthorized = false;
                    }
                }
            }
            else
            {
                isRoleBasedAuthorized = true;
            }



            //check if the user is Authenticated (Signed In) using the User Identity which checks the AspNetCore Identity Cookie included in the request.
            //(remember that when the user logs in, a cookie is created and saved in the browser to hold his info)
            //And check the user's Roles.
            //Then allow to continue the http request to the method, or redirect him to login page:
            if (context.HttpContext.User.Identity.IsAuthenticated == false)
            {
                //check if the the request is an Ajax request (it has the word "XMLHttpRequest" in its header):
                if (context.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
                {
                    var loginUrl = "/Account/Login";

                    //if not authenticated and the request is ajax, make the status code = 401 and save the redirect link in the result:
                    context.HttpContext.Response.StatusCode = 401;
                    //context.HttpContext.Response.SuppressFormsAuthenticationRedirect = true
                    JsonResult jsonResult1 = new JsonResult(new { redirectUrl = loginUrl });
                    context.Result = jsonResult1;
                    //then this will be intercepted in ajaxErrorHandler in wwwroot/js folder in order to redirect.

                    //return nothing !
                    return;
                }
                //if the request is not an ajax:
                else
                {
                    var loginUrl = $"/Account/Login";
                    //if the user is not authenticated and the request is not Ajax, simply redirect from here:
                    context.Result = new RedirectResult(loginUrl);

                    return;
                }
            }
            //if the user is authenticated, and Role-based authorized, simply pass the http request to the method:
            else if (context.HttpContext.User.Identity.IsAuthenticated == true && isRoleBasedAuthorized == true)
            {
                await next();

                return;
            }

            //the code reaches this area in
            //the last case which is that user is authenticated, but his role does not match Roles.
            context.HttpContext.Response.StatusCode = 403;  //403 is Authenticated, but no permissions.
            var        _errorMessage = " Authorized, you are not !";
            JsonResult jsonResult2   = new JsonResult(new { errorMessage = _errorMessage });

            context.Result = jsonResult2;
            //returns nothing:
            return;
        }
コード例 #49
0
ファイル: Includes.cs プロジェクト: daniefer/samples
        public override async Task OnActionExecutionAsync(ActionExecutingContext actionContext, ActionExecutionDelegate next)
        {
            var stopwatch = System.Diagnostics.Stopwatch.StartNew();

            await next();

            stopwatch.Stop();
            actionContext.HttpContext.Response.Headers.Add("x-time-elapsed", stopwatch.Elapsed.ToString());
        }
コード例 #50
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var user = context.HttpContext.User;

            var appName = context.RouteData.Values["app"]?.ToString();

            if (!string.IsNullOrWhiteSpace(appName))
            {
                var isFrontend = user.IsInClient(DefaultClients.Frontend);

                var app = await appProvider.GetAppAsync(appName, !isFrontend);

                if (app == null)
                {
                    context.Result = new NotFoundResult();
                    return;
                }

                var(role, permissions) = FindByOpenIdSubject(app, user, isFrontend);

                if (permissions == null)
                {
                    (role, permissions) = FindByOpenIdClient(app, user, isFrontend);
                }

                if (permissions == null)
                {
                    (role, permissions) = FindAnonymousClient(app, isFrontend);
                }

                if (permissions != null)
                {
                    var identity = user.Identities.First();

                    if (!string.IsNullOrWhiteSpace(role))
                    {
                        identity.AddClaim(new Claim(ClaimTypes.Role, role));
                    }

                    foreach (var permission in permissions)
                    {
                        identity.AddClaim(new Claim(SquidexClaimTypes.Permissions, permission.Id));
                    }
                }

                var requestContext = SetContext(context.HttpContext, app);

                if (!AllowAnonymous(context) && !HasPermission(appName, requestContext))
                {
                    if (string.IsNullOrWhiteSpace(user.Identity.AuthenticationType))
                    {
                        context.Result = new UnauthorizedResult();
                    }
                    else
                    {
                        context.Result = new NotFoundResult();
                    }

                    return;
                }

                context.HttpContext.Features.Set <IAppFeature>(new AppFeature(app.NamedId()));
                context.HttpContext.Response.Headers.Add("X-AppId", app.Id.ToString());
            }
            else
            {
                SetContext(context.HttpContext, null !);
            }

            await next();
        }
コード例 #51
0
        async System.Threading.Tasks.Task IAsyncActionFilter.OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (!context.HttpContext.Request.Headers.TryGetValue(APIKEYNAME, out var extractedApiKey))
            {
                context.Result = new ContentResult()
                {
                    StatusCode = 401,
                    Content    = "Api Key was not provided"
                };
                return;
            }

            var appSettings = context.HttpContext.RequestServices.GetRequiredService <IConfiguration>();

            var apiKey = appSettings.GetValue <string>(APIKEYNAME);

            if (!apiKey.Equals(extractedApiKey))
            {
                context.Result = new ContentResult()
                {
                    StatusCode = 401,
                    Content    = "Api Key is not valid"
                };
                return;
            }

            await next();
        }
コード例 #52
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            recorderContext.ActionExecutingContext = context;

            recorderContext.ActionExecutedContext = await next();
        }
コード例 #53
0
        public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var httpContext = context.HttpContext;
            var result      = await httpContext.AuthenticateAsync("Bearer");

            httpContext.User = result.Principal;
            var username = httpContext.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value
                           ?? httpContext.User?.Claims.Where(x => x.Type == "preferred_username").FirstOrDefault()?.Value;
            var isApi = username == null && httpContext.User != null && httpContext.User.Identity.IsAuthenticated;

            if (!isApi)
            {
                var svc = context.HttpContext.RequestServices;
                IApplicationRepository applicationRepository = svc.GetService(typeof(IApplicationRepository)) as IApplicationRepository;
                IConfigurationService  configurationService  = svc.GetService(typeof(IConfigurationService)) as IConfigurationService;
                var contextData = httpContext.GetRouteData();
                if (contextData != null &&
                    contextData.Values.ContainsKey(ROUTE_PARAM) &&
                    (httpContext.Request.Method.Equals("POST") ||
                     httpContext.Request.Method.Equals("PATCH") ||
                     httpContext.Request.Method.Equals("PUT") ||
                     httpContext.Request.Method.Equals("DELETE")))
                {
                    var  applicationNumber     = contextData.Values[ROUTE_PARAM].ToString();
                    long applicationNumberLong = long.Parse(applicationNumber);
                    var  application           = await applicationRepository.GetAsync(applicationNumberLong);

                    var phase  = application.Phase;
                    var status = EnumUtils.ToEnumString(application.Status);

                    var router = (MvcAttributeRouteHandler)contextData.Routers.FirstOrDefault(r => r is MvcAttributeRouteHandler);
                    if (router != null && router.Actions.Count() > 0)
                    {
                        var endpoint = ReplaceParamTypes(router.Actions[0].AttributeRouteInfo.Template);
                        endpoint = TrimStart(endpoint, "v1/offer/");
                        endpoint = TrimStart(endpoint, "v2/offer/");

                        if (phase != null)
                        {
                            var blockedUrlsData = await configurationService.GetEffective("offer/data-lock-rules/" + phase, "[]");

                            List <RouteFilterConfiguration> blockedUrls = JArray.Parse(blockedUrlsData).ToObject <List <RouteFilterConfiguration> >();
                            if (blockedUrls.Any(x => x.Route.Equals(endpoint) && x.Method.Equals(httpContext.Request.Method)))
                            {
                                context.Result = new StatusCodeResult(403);
                                return;
                            }
                        }
                    }
                }
            }
            await next();
        }
コード例 #54
0
        public override async Task OnActionExecutionAsync(ActionExecutingContext actionContext, ActionExecutionDelegate next)
        {
            var scriptHostManager = (WebScriptHostManager)actionContext.HttpContext.Items[ScriptConstants.AzureFunctionsHostManagerKey];

            scriptHostManager.Instance?.NotifyDebug();

            await next();
        }
コード例 #55
0
        public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var request = context.HttpContext.Request;

            if (this.IsAjaxRequest(request))
            {
                await next();
            }

            else
            {
                context.Result = new ForbidResult();
            }
        }
コード例 #56
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            //var workerUserId = string.Empty;

            //if (APIConfig.GetInstance().Environment != "localhost")
            //{
            //if (MyHttpContext.Current.Request == null || MyHttpContext.Current.Request.Headers == null)
            //    throw new ParamErrorException("Request不存在");

            //if (!MyHttpContext.Current.Request.Headers.ContainsKey("Token"))
            //    throw new ParamErrorException("Token获取失败!");

            //var token = MyHttpContext.Current.Request.Headers["Token"].First();
            //if (string.IsNullOrEmpty(token))
            //    throw new ParamErrorException("Token获取失败!");

            //workerUserId = result.resultData;
            //}
            //else
            //{
            //    //TODO:测试专用代码
            //    workerUserId = "jiangjun.yang";
            //}

            //if (string.IsNullOrEmpty(workerUserId))
            //{
            //    throw new NoPermissionException("Token获取失败!");
            //}

            //把用户信息存入本次请求中
            //context.RouteData.Values[nameof(ConstantConfig.PeopleInfo)] = user.UserInfo;

            await base.OnActionExecutionAsync(context, next);
        }
コード例 #57
0
        async Task IAsyncActionFilter.OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (!context.HttpContext.Request.Headers.TryGetValue(ApiKeyHeaderName, out var clientKey))
            {
                context.Result = new UnauthorizedResult();
                return;
            }

            var config = context.HttpContext.RequestServices.GetRequiredService<IConfiguration>();
            var apiKey = config.GetValue<string>(key: ApiKeyHeaderName);

            if (!apiKey.Equals(clientKey))
            {
                context.Result = new UnauthorizedResult();
                return;
            }

            await next();
        }
コード例 #58
0
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            await LoadHotVacanciesToViewData();

            await base.OnActionExecutionAsync(context, next);
        }
コード例 #59
0
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            IIdentityService svc = context.HttpContext.RequestServices.GetRequiredService <IIdentityService>();
            var user             = svc.GetAuthenticatedUser();

            if (user == null)
            {
                context.Result = this.CreateInvalidResult();
            }
            else
            {
                IPermissionService permissionSvc = context.HttpContext.RequestServices.GetRequiredService <IPermissionService>();
                if (!(await permissionSvc.HasPermissionAsync(PermiasionName, user.Id)))
                {
                    context.Result = this.CreateInvalidResult();
                }
            }
            await base.OnActionExecutionAsync(context, next);
        }