コード例 #1
0
ファイル: ConsumesAttribute.cs プロジェクト: huoxudong125/Mvc
 /// <inheritdoc />
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     if (context == null)
     {
         throw new ArgumentNullException(nameof(context));
     }
 }
コード例 #2
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     if (!String.IsNullOrEmpty(_cacheKey) &&
         !_cache.ContainsKey(_cacheKey))
     {
         var result = context.Result as ContentResult;
         if (result != null)
         {
             _cache.Add(_cacheKey, result.Content);
         }
     }
 }
コード例 #3
0
 /// <inheritdoc />
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     _tempData.Save();
 }
コード例 #4
0
ファイル: ResourceFilter.cs プロジェクト: IsaacTai123/repos
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     context.HttpContext.Response.WriteAsync($"{GetType().Name} out. \r\n");
 }
コード例 #5
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     logger.LogInformation("ResourceFilter Executed!");
 }
コード例 #6
0
        private Task Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
        {
            switch (next)
            {
            case State.InvokeBegin:
            {
                goto case State.AuthorizationBegin;
            }

            case State.AuthorizationBegin:
            {
                _cursor.Reset();
                goto case State.AuthorizationNext;
            }

            case State.AuthorizationNext:
            {
                var current = _cursor.GetNextFilter <IAuthorizationFilter, IAsyncAuthorizationFilter>();
                if (current.FilterAsync != null)
                {
                    if (_authorizationContext == null)
                    {
                        _authorizationContext = new AuthorizationFilterContext(_actionContext, _filters);
                    }

                    state = current.FilterAsync;
                    goto case State.AuthorizationAsyncBegin;
                }
                else if (current.Filter != null)
                {
                    if (_authorizationContext == null)
                    {
                        _authorizationContext = new AuthorizationFilterContext(_actionContext, _filters);
                    }

                    state = current.Filter;
                    goto case State.AuthorizationSync;
                }
                else
                {
                    goto case State.AuthorizationEnd;
                }
            }

            case State.AuthorizationAsyncBegin:
            {
                Debug.Assert(_authorizationContext != null);

                var filter = (IAsyncAuthorizationFilter)state;
                var authorizationContext = _authorizationContext;

                _diagnosticSource.BeforeOnAuthorizationAsync(authorizationContext, filter);

                var task = filter.OnAuthorizationAsync(authorizationContext);
                if (task.Status != TaskStatus.RanToCompletion)
                {
                    next = State.AuthorizationAsyncEnd;
                    return(task);
                }

                goto case State.AuthorizationAsyncEnd;
            }

            case State.AuthorizationAsyncEnd:
            {
                var filter = (IAsyncAuthorizationFilter)state;
                var authorizationContext = _authorizationContext;

                _diagnosticSource.AfterOnAuthorizationAsync(authorizationContext, filter);

                if (authorizationContext.Result != null)
                {
                    goto case State.AuthorizationShortCircuit;
                }

                goto case State.AuthorizationNext;
            }

            case State.AuthorizationSync:
            {
                Debug.Assert(_authorizationContext != null);

                var filter = (IAuthorizationFilter)state;
                var authorizationContext = _authorizationContext;

                _diagnosticSource.BeforeOnAuthorization(authorizationContext, filter);

                filter.OnAuthorization(authorizationContext);

                _diagnosticSource.AfterOnAuthorization(authorizationContext, filter);

                if (authorizationContext.Result != null)
                {
                    goto case State.AuthorizationShortCircuit;
                }

                goto case State.AuthorizationNext;
            }

            case State.AuthorizationShortCircuit:
            {
                // If an authorization filter short circuits, the result is the last thing we execute
                // so just return that task instead of calling back into the state machine.
                isCompleted = true;
                return(InvokeResultAsync(_authorizationContext.Result));
            }

            case State.AuthorizationEnd:
            {
                goto case State.ResourceBegin;
            }

            case State.ResourceBegin:
            {
                _cursor.Reset();
                goto case State.ResourceNext;
            }

            case State.ResourceNext:
            {
                var current = _cursor.GetNextFilter <IResourceFilter, IAsyncResourceFilter>();
                if (current.FilterAsync != null)
                {
                    if (_resourceExecutingContext == null)
                    {
                        _resourceExecutingContext = new ResourceExecutingContext(
                            _actionContext,
                            _filters,
                            _valueProviderFactories);
                    }

                    state = current.FilterAsync;
                    goto case State.ResourceAsyncBegin;
                }
                else if (current.Filter != null)
                {
                    if (_resourceExecutingContext == null)
                    {
                        _resourceExecutingContext = new ResourceExecutingContext(
                            _actionContext,
                            _filters,
                            _valueProviderFactories);
                    }

                    state = current.Filter;
                    goto case State.ResourceSyncBegin;
                }
                else if (scope == Scope.Resource)
                {
                    Debug.Assert(_resourceExecutingContext != null);
                    goto case State.ResourceInside;
                }
                else
                {
                    Debug.Assert(scope == Scope.Invoker);
                    goto case State.PageBegin;
                }
            }

            case State.ResourceAsyncBegin:
            {
                Debug.Assert(_resourceExecutingContext != null);

                var filter = (IAsyncResourceFilter)state;
                var resourceExecutingContext = _resourceExecutingContext;

                _diagnosticSource.BeforeOnResourceExecution(resourceExecutingContext, filter);

                var task = filter.OnResourceExecutionAsync(resourceExecutingContext, InvokeNextResourceFilterAwaitedAsync);
                if (task.Status != TaskStatus.RanToCompletion)
                {
                    next = State.ResourceAsyncEnd;
                    return(task);
                }

                goto case State.ResourceAsyncEnd;
            }

            case State.ResourceAsyncEnd:
            {
                var filter = (IAsyncResourceFilter)state;
                if (_resourceExecutedContext == null)
                {
                    // If we get here then the filter didn't call 'next' indicating a short circuit
                    Debug.Assert(_resourceExecutingContext.Result != null);
                    _resourceExecutedContext = new ResourceExecutedContext(_resourceExecutingContext, _filters)
                    {
                        Canceled = true,
                        Result   = _resourceExecutingContext.Result,       // Can be null
                    };
                }

                _diagnosticSource.AfterOnResourceExecution(_resourceExecutedContext, filter);

                if (_resourceExecutingContext.Result != null)
                {
                    goto case State.ResourceShortCircuit;
                }

                goto case State.ResourceEnd;
            }

            case State.ResourceSyncBegin:
            {
                Debug.Assert(_resourceExecutingContext != null);

                var filter = (IResourceFilter)state;
                var resourceExecutingContext = _resourceExecutingContext;

                _diagnosticSource.BeforeOnResourceExecuting(resourceExecutingContext, filter);

                filter.OnResourceExecuting(resourceExecutingContext);

                _diagnosticSource.AfterOnResourceExecuting(resourceExecutingContext, filter);

                if (resourceExecutingContext.Result != null)
                {
                    _resourceExecutedContext = new ResourceExecutedContext(resourceExecutingContext, _filters)
                    {
                        Canceled = true,
                        Result   = _resourceExecutingContext.Result,
                    };

                    goto case State.ResourceShortCircuit;
                }

                var task = InvokeNextResourceFilter();
                if (task.Status != TaskStatus.RanToCompletion)
                {
                    next = State.ResourceSyncEnd;
                    return(task);
                }

                goto case State.ResourceSyncEnd;
            }

            case State.ResourceSyncEnd:
            {
                var filter = (IResourceFilter)state;
                var resourceExecutedContext = _resourceExecutedContext;

                _diagnosticSource.BeforeOnResourceExecuted(resourceExecutedContext, filter);

                filter.OnResourceExecuted(resourceExecutedContext);

                _diagnosticSource.AfterOnResourceExecuted(resourceExecutedContext, filter);

                goto case State.ResourceEnd;
            }

            case State.ResourceShortCircuit:
            {
                Debug.Assert(_resourceExecutedContext != null);

                var task = InvokeResultAsync(_resourceExecutingContext.Result);
                if (task.Status != TaskStatus.RanToCompletion)
                {
                    next = State.ResourceEnd;
                    return(task);
                }

                goto case State.ResourceEnd;
            }

            case State.ResourceInside:
            {
                goto case State.PageBegin;
            }

            case State.ResourceEnd:
            {
                if (scope == Scope.Resource)
                {
                    isCompleted = true;
                    return(TaskCache.CompletedTask);
                }

                Debug.Assert(scope == Scope.Invoker);
                Rethrow(_resourceExecutedContext);

                goto case State.InvokeEnd;
            }

            case State.PageBegin:
            {
                next = State.PageEnd;
                return(ExecutePageAsync());
            }

            case State.PageEnd:
            {
                if (scope == Scope.Resource)
                {
                    Debug.Assert(_resourceExecutedContext == null);
                    _resourceExecutedContext = new ResourceExecutedContext(_actionContext, _filters);

                    isCompleted = true;
                    return(TaskCache.CompletedTask);
                }

                Debug.Assert(scope == Scope.Invoker);
                goto case State.InvokeEnd;
            }

            case State.InvokeEnd:
            {
                isCompleted = true;
                return(TaskCache.CompletedTask);
            }
            }

            return(ExecutePageAsync());
        }
コード例 #7
0
 /// <summary>
 /// 资源过滤器后置方法,当所有处理返回时执行,然后返回的中间件管道
 /// </summary>
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     Console.WriteLine("==== OnResourceExecuted========");
     //throw new Exception("OnResourceExecuted有异常");
 }
コード例 #8
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     throw new NotImplementedException();
 }
コード例 #9
0
        private async Task <ResourceExecutedContext> InvokeResourceFilterAsync()
        {
            Debug.Assert(_resourceExecutingContext != null);

            if (_resourceExecutingContext.Result != null)
            {
                // If we get here, it means that an async filter set a result AND called next(). This is forbidden.
                var message = Resources.FormatAsyncResourceFilter_InvalidShortCircuit(
                    typeof(IAsyncResourceFilter).Name,
                    nameof(ResourceExecutingContext.Result),
                    typeof(ResourceExecutingContext).Name,
                    typeof(ResourceExecutionDelegate).Name);

                throw new InvalidOperationException(message);
            }

            var item = _cursor.GetNextFilter <IResourceFilter, IAsyncResourceFilter>();

            try
            {
                if (item.FilterAsync != null)
                {
                    await item.FilterAsync.OnResourceExecutionAsync(
                        _resourceExecutingContext,
                        InvokeResourceFilterAsync);

                    if (_resourceExecutedContext == null)
                    {
                        // If we get here then the filter didn't call 'next' indicating a short circuit
                        if (_resourceExecutingContext.Result != null)
                        {
                            _logger.LogVerbose(
                                ResourceFilterShortCircuitLogMessage,
                                item.FilterAsync.GetType().FullName);

                            await InvokeResultAsync(_resourceExecutingContext.Result);
                        }

                        _resourceExecutedContext = new ResourceExecutedContext(_resourceExecutingContext, _filters)
                        {
                            Canceled = true,
                            Result   = _resourceExecutingContext.Result,
                        };
                    }
                }
                else if (item.Filter != null)
                {
                    item.Filter.OnResourceExecuting(_resourceExecutingContext);

                    if (_resourceExecutingContext.Result != null)
                    {
                        // Short-circuited by setting a result.

                        _logger.LogVerbose(ResourceFilterShortCircuitLogMessage, item.Filter.GetType().FullName);

                        await InvokeResultAsync(_resourceExecutingContext.Result);

                        _resourceExecutedContext = new ResourceExecutedContext(_resourceExecutingContext, _filters)
                        {
                            Canceled = true,
                            Result   = _resourceExecutingContext.Result,
                        };
                    }
                    else
                    {
                        item.Filter.OnResourceExecuted(await InvokeResourceFilterAsync());
                    }
                }
                else
                {
                    // We've reached the end of resource filters, so move to setting up state to invoke model
                    // binding.
                    ActionBindingContext = new ActionBindingContext();
                    ActionBindingContext.InputFormatters   = _resourceExecutingContext.InputFormatters;
                    ActionBindingContext.OutputFormatters  = _resourceExecutingContext.OutputFormatters;
                    ActionBindingContext.ModelBinder       = new CompositeModelBinder(_resourceExecutingContext.ModelBinders);
                    ActionBindingContext.ValidatorProvider = new CompositeModelValidatorProvider(
                        _resourceExecutingContext.ValidatorProviders);

                    var valueProviderFactoryContext = new ValueProviderFactoryContext(
                        ActionContext.HttpContext,
                        ActionContext.RouteData.Values);

                    ActionBindingContext.ValueProvider = await CompositeValueProvider.CreateAsync(
                        _resourceExecutingContext.ValueProviderFactories,
                        valueProviderFactoryContext);

                    // >> ExceptionFilters >> Model Binding >> ActionFilters >> Action
                    await InvokeAllExceptionFiltersAsync();

                    // If Exception Filters provide a result, it's a short-circuit due to an exception.
                    // We don't execute Result Filters around the result.
                    Debug.Assert(_exceptionContext != null);
                    if (_exceptionContext.Result != null)
                    {
                        // This means that exception filters returned a result to 'handle' an error.
                        // We're not interested in seeing the exception details since it was handled.
                        await InvokeResultAsync(_exceptionContext.Result);

                        _resourceExecutedContext = new ResourceExecutedContext(_resourceExecutingContext, _filters)
                        {
                            Result = _exceptionContext.Result,
                        };
                    }
                    else if (_exceptionContext.Exception != null)
                    {
                        // If we get here, this means that we have an unhandled exception.
                        // Exception filted didn't handle this, so send it on to resource filters.
                        _resourceExecutedContext = new ResourceExecutedContext(_resourceExecutingContext, _filters);

                        // Preserve the stack trace if possible.
                        _resourceExecutedContext.Exception = _exceptionContext.Exception;
                        if (_exceptionContext.ExceptionDispatchInfo != null)
                        {
                            _resourceExecutedContext.ExceptionDispatchInfo = _exceptionContext.ExceptionDispatchInfo;
                        }
                    }
                    else
                    {
                        // We have a successful 'result' from the action or an Action Filter, so run
                        // Result Filters.
                        Debug.Assert(_actionExecutedContext != null);
                        var result = _actionExecutedContext.Result;

                        // >> ResultFilters >> (Result)
                        await InvokeAllResultFiltersAsync(result);

                        _resourceExecutedContext = new ResourceExecutedContext(_resourceExecutingContext, _filters)
                        {
                            Result = _resultExecutedContext.Result,
                        };
                    }
                }
            }
            catch (Exception exception)
            {
                _resourceExecutedContext = new ResourceExecutedContext(_resourceExecutingContext, _filters)
                {
                    ExceptionDispatchInfo = ExceptionDispatchInfo.Capture(exception)
                };
            }

            Debug.Assert(_resourceExecutedContext != null);
            return(_resourceExecutedContext);
        }
コード例 #10
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     _logger.LogInformation($"OnResourceExecuted - {DateTime.Now}");
 }
コード例 #11
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     // do nothing
 }
コード例 #12
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     this.logger.LogInformation($"OnResourceExecuting: {context.Result?.GetType().Name}");
 }
コード例 #13
0
ファイル: SignumFilters.cs プロジェクト: goldenauge/framework
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     CultureInfo.CurrentUICulture = context.HttpContext.Items[UICulture_Key] as CultureInfo ?? CultureInfo.CurrentUICulture;
     CultureInfo.CurrentCulture   = context.HttpContext.Items[Culture_Key] as CultureInfo ?? CultureInfo.CurrentCulture;
 }
コード例 #14
0
ファイル: SignumFilters.cs プロジェクト: goldenauge/framework
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     Statics.CleanThreadContextAndAssert();
 }
コード例 #15
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     Console.WriteLine($"Executing IResourceFilter.OnResourceExecuted: cancelled {context.Canceled}");
 }
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     Log("OnResourceExecuted done");
 }
コード例 #17
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     Task.Delay(_Calculator.GetDelay()).GetAwaiter().GetResult();
 }
コード例 #18
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     _logger.LogInformation($"Path - {context.HttpContext.Request.Path}");
     _logger.LogInformation($"OnResourceExecuted - {DateTime.Now}");
 }
コード例 #19
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     Dictionary.Add(context.HttpContext.Request.Path, context.Result);
 }
コード例 #20
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     context.HttpContext.Response.WriteAsync("Resuorce excuting.");
 }
コード例 #21
0
 private bool ExpectsJsonResult(ResourceExecutedContext context)
 {
     return(context.ActionDescriptor is ControllerActionDescriptor cad &&
            !typeof(IActionResult).IsAssignableFrom(cad.MethodInfo.ReturnType));
 }
コード例 #22
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     logger.LogInformation($"LOGGER!!!{context.Result.GetType().Name}");
 }
コード例 #23
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     //nothing to do here. part of IResourceFilter implementation
 }
コード例 #24
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     // This will work as default.
 }
コード例 #25
0
 /// <summary>
 /// 获取资源后拦截
 /// </summary>
 /// <param name="context"></param>
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     Console.WriteLine("资源拦截执行后");
 }
コード例 #26
0
ファイル: ResourceInvoker.cs プロジェクト: poke/aspnet_Mvc
        private Task Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
        {
            switch (next)
            {
            case State.InvokeBegin:
            {
                goto case State.AuthorizationBegin;
            }

            case State.AuthorizationBegin:
            {
                _cursor.Reset();
                goto case State.AuthorizationNext;
            }

            case State.AuthorizationNext:
            {
                var current = _cursor.GetNextFilter <IAuthorizationFilter, IAsyncAuthorizationFilter>();
                if (current.FilterAsync != null)
                {
                    if (_authorizationContext == null)
                    {
                        _authorizationContext = new AuthorizationFilterContext(_actionContext, _filters);
                    }

                    state = current.FilterAsync;
                    goto case State.AuthorizationAsyncBegin;
                }
                else if (current.Filter != null)
                {
                    if (_authorizationContext == null)
                    {
                        _authorizationContext = new AuthorizationFilterContext(_actionContext, _filters);
                    }

                    state = current.Filter;
                    goto case State.AuthorizationSync;
                }
                else
                {
                    goto case State.AuthorizationEnd;
                }
            }

            case State.AuthorizationAsyncBegin:
            {
                Debug.Assert(state != null);
                Debug.Assert(_authorizationContext != null);

                var filter = (IAsyncAuthorizationFilter)state;
                var authorizationContext = _authorizationContext;

                _diagnosticSource.BeforeOnAuthorizationAsync(authorizationContext, filter);
                _logger.BeforeExecutingMethodOnFilter(
                    FilterTypeConstants.AuthorizationFilter,
                    nameof(IAsyncAuthorizationFilter.OnAuthorizationAsync),
                    filter);

                var task = filter.OnAuthorizationAsync(authorizationContext);
                if (task.Status != TaskStatus.RanToCompletion)
                {
                    next = State.AuthorizationAsyncEnd;
                    return(task);
                }

                goto case State.AuthorizationAsyncEnd;
            }

            case State.AuthorizationAsyncEnd:
            {
                Debug.Assert(state != null);
                Debug.Assert(_authorizationContext != null);

                var filter = (IAsyncAuthorizationFilter)state;
                var authorizationContext = _authorizationContext;

                _diagnosticSource.AfterOnAuthorizationAsync(authorizationContext, filter);
                _logger.AfterExecutingMethodOnFilter(
                    FilterTypeConstants.AuthorizationFilter,
                    nameof(IAsyncAuthorizationFilter.OnAuthorizationAsync),
                    filter);

                if (authorizationContext.Result != null)
                {
                    goto case State.AuthorizationShortCircuit;
                }

                goto case State.AuthorizationNext;
            }

            case State.AuthorizationSync:
            {
                Debug.Assert(state != null);
                Debug.Assert(_authorizationContext != null);

                var filter = (IAuthorizationFilter)state;
                var authorizationContext = _authorizationContext;

                _diagnosticSource.BeforeOnAuthorization(authorizationContext, filter);
                _logger.BeforeExecutingMethodOnFilter(
                    FilterTypeConstants.AuthorizationFilter,
                    nameof(IAuthorizationFilter.OnAuthorization),
                    filter);

                filter.OnAuthorization(authorizationContext);

                _diagnosticSource.AfterOnAuthorization(authorizationContext, filter);
                _logger.AfterExecutingMethodOnFilter(
                    FilterTypeConstants.AuthorizationFilter,
                    nameof(IAuthorizationFilter.OnAuthorization),
                    filter);

                if (authorizationContext.Result != null)
                {
                    goto case State.AuthorizationShortCircuit;
                }

                goto case State.AuthorizationNext;
            }

            case State.AuthorizationShortCircuit:
            {
                Debug.Assert(state != null);
                Debug.Assert(_authorizationContext != null);
                Debug.Assert(_authorizationContext.Result != null);

                _logger.AuthorizationFailure((IFilterMetadata)state);

                // This is a short-circuit - execute relevant result filters + result and complete this invocation.
                isCompleted = true;
                _result     = _authorizationContext.Result;
                return(InvokeAlwaysRunResultFilters());
            }

            case State.AuthorizationEnd:
            {
                goto case State.ResourceBegin;
            }

            case State.ResourceBegin:
            {
                _cursor.Reset();
                goto case State.ResourceNext;
            }

            case State.ResourceNext:
            {
                var current = _cursor.GetNextFilter <IResourceFilter, IAsyncResourceFilter>();
                if (current.FilterAsync != null)
                {
                    if (_resourceExecutingContext == null)
                    {
                        _resourceExecutingContext = new ResourceExecutingContext(
                            _actionContext,
                            _filters,
                            _valueProviderFactories);
                    }

                    state = current.FilterAsync;
                    goto case State.ResourceAsyncBegin;
                }
                else if (current.Filter != null)
                {
                    if (_resourceExecutingContext == null)
                    {
                        _resourceExecutingContext = new ResourceExecutingContext(
                            _actionContext,
                            _filters,
                            _valueProviderFactories);
                    }

                    state = current.Filter;
                    goto case State.ResourceSyncBegin;
                }
                else
                {
                    // All resource filters are currently on the stack - now execute the 'inside'.
                    goto case State.ResourceInside;
                }
            }

            case State.ResourceAsyncBegin:
            {
                Debug.Assert(state != null);
                Debug.Assert(_resourceExecutingContext != null);

                var filter = (IAsyncResourceFilter)state;
                var resourceExecutingContext = _resourceExecutingContext;

                _diagnosticSource.BeforeOnResourceExecution(resourceExecutingContext, filter);
                _logger.BeforeExecutingMethodOnFilter(
                    FilterTypeConstants.ResourceFilter,
                    nameof(IAsyncResourceFilter.OnResourceExecutionAsync),
                    filter);

                var task = filter.OnResourceExecutionAsync(resourceExecutingContext, InvokeNextResourceFilterAwaitedAsync);
                if (task.Status != TaskStatus.RanToCompletion)
                {
                    next = State.ResourceAsyncEnd;
                    return(task);
                }

                goto case State.ResourceAsyncEnd;
            }

            case State.ResourceAsyncEnd:
            {
                Debug.Assert(state != null);
                Debug.Assert(_resourceExecutingContext != null);

                var filter = (IAsyncResourceFilter)state;
                if (_resourceExecutedContext == null)
                {
                    // If we get here then the filter didn't call 'next' indicating a short circuit.
                    _resourceExecutedContext = new ResourceExecutedContext(_resourceExecutingContext, _filters)
                    {
                        Canceled = true,
                        Result   = _resourceExecutingContext.Result,
                    };

                    _diagnosticSource.AfterOnResourceExecution(_resourceExecutedContext, filter);
                    _logger.AfterExecutingMethodOnFilter(
                        FilterTypeConstants.ResourceFilter,
                        nameof(IAsyncResourceFilter.OnResourceExecutionAsync),
                        filter);

                    // A filter could complete a Task without setting a result
                    if (_resourceExecutingContext.Result != null)
                    {
                        goto case State.ResourceShortCircuit;
                    }
                }

                goto case State.ResourceEnd;
            }

            case State.ResourceSyncBegin:
            {
                Debug.Assert(state != null);
                Debug.Assert(_resourceExecutingContext != null);

                var filter = (IResourceFilter)state;
                var resourceExecutingContext = _resourceExecutingContext;

                _diagnosticSource.BeforeOnResourceExecuting(resourceExecutingContext, filter);
                _logger.BeforeExecutingMethodOnFilter(
                    FilterTypeConstants.ResourceFilter,
                    nameof(IResourceFilter.OnResourceExecuting),
                    filter);

                filter.OnResourceExecuting(resourceExecutingContext);

                _diagnosticSource.AfterOnResourceExecuting(resourceExecutingContext, filter);
                _logger.AfterExecutingMethodOnFilter(
                    FilterTypeConstants.ResourceFilter,
                    nameof(IResourceFilter.OnResourceExecuting),
                    filter);

                if (resourceExecutingContext.Result != null)
                {
                    _resourceExecutedContext = new ResourceExecutedContext(resourceExecutingContext, _filters)
                    {
                        Canceled = true,
                        Result   = _resourceExecutingContext.Result,
                    };

                    goto case State.ResourceShortCircuit;
                }

                var task = InvokeNextResourceFilter();
                if (task.Status != TaskStatus.RanToCompletion)
                {
                    next = State.ResourceSyncEnd;
                    return(task);
                }

                goto case State.ResourceSyncEnd;
            }

            case State.ResourceSyncEnd:
            {
                Debug.Assert(state != null);
                Debug.Assert(_resourceExecutingContext != null);
                Debug.Assert(_resourceExecutedContext != null);

                var filter = (IResourceFilter)state;
                var resourceExecutedContext = _resourceExecutedContext;

                _diagnosticSource.BeforeOnResourceExecuted(resourceExecutedContext, filter);
                _logger.BeforeExecutingMethodOnFilter(
                    FilterTypeConstants.ResourceFilter,
                    nameof(IResourceFilter.OnResourceExecuted),
                    filter);

                filter.OnResourceExecuted(resourceExecutedContext);

                _diagnosticSource.AfterOnResourceExecuted(resourceExecutedContext, filter);
                _logger.AfterExecutingMethodOnFilter(
                    FilterTypeConstants.ResourceFilter,
                    nameof(IResourceFilter.OnResourceExecuted),
                    filter);

                goto case State.ResourceEnd;
            }

            case State.ResourceShortCircuit:
            {
                Debug.Assert(state != null);
                Debug.Assert(_resourceExecutingContext != null);
                Debug.Assert(_resourceExecutedContext != null);

                _logger.ResourceFilterShortCircuited((IFilterMetadata)state);

                _result = _resourceExecutingContext.Result;
                var task = InvokeAlwaysRunResultFilters();
                if (task.Status != TaskStatus.RanToCompletion)
                {
                    next = State.ResourceEnd;
                    return(task);
                }

                goto case State.ResourceEnd;
            }

            case State.ResourceInside:
            {
                goto case State.ExceptionBegin;
            }

            case State.ExceptionBegin:
            {
                _cursor.Reset();
                goto case State.ExceptionNext;
            }

            case State.ExceptionNext:
            {
                var current = _cursor.GetNextFilter <IExceptionFilter, IAsyncExceptionFilter>();
                if (current.FilterAsync != null)
                {
                    state = current.FilterAsync;
                    goto case State.ExceptionAsyncBegin;
                }
                else if (current.Filter != null)
                {
                    state = current.Filter;
                    goto case State.ExceptionSyncBegin;
                }
                else if (scope == Scope.Exception)
                {
                    // All exception filters are on the stack already - so execute the 'inside'.
                    goto case State.ExceptionInside;
                }
                else
                {
                    // There are no exception filters - so jump right to the action.
                    Debug.Assert(scope == Scope.Invoker || scope == Scope.Resource);
                    goto case State.ActionBegin;
                }
            }

            case State.ExceptionAsyncBegin:
            {
                var task = InvokeNextExceptionFilterAsync();
                if (task.Status != TaskStatus.RanToCompletion)
                {
                    next = State.ExceptionAsyncResume;
                    return(task);
                }

                goto case State.ExceptionAsyncResume;
            }

            case State.ExceptionAsyncResume:
            {
                Debug.Assert(state != null);

                var filter           = (IAsyncExceptionFilter)state;
                var exceptionContext = _exceptionContext;

                // When we get here we're 'unwinding' the stack of exception filters. If we have an unhandled exception,
                // we'll call the filter. Otherwise there's nothing to do.
                if (exceptionContext?.Exception != null && !exceptionContext.ExceptionHandled)
                {
                    _diagnosticSource.BeforeOnExceptionAsync(exceptionContext, filter);
                    _logger.BeforeExecutingMethodOnFilter(
                        FilterTypeConstants.ExceptionFilter,
                        nameof(IAsyncExceptionFilter.OnExceptionAsync),
                        filter);

                    var task = filter.OnExceptionAsync(exceptionContext);
                    if (task.Status != TaskStatus.RanToCompletion)
                    {
                        next = State.ExceptionAsyncEnd;
                        return(task);
                    }

                    goto case State.ExceptionAsyncEnd;
                }

                goto case State.ExceptionEnd;
            }

            case State.ExceptionAsyncEnd:
            {
                Debug.Assert(state != null);
                Debug.Assert(_exceptionContext != null);

                var filter           = (IAsyncExceptionFilter)state;
                var exceptionContext = _exceptionContext;

                _diagnosticSource.AfterOnExceptionAsync(exceptionContext, filter);
                _logger.AfterExecutingMethodOnFilter(
                    FilterTypeConstants.ExceptionFilter,
                    nameof(IAsyncExceptionFilter.OnExceptionAsync),
                    filter);

                if (exceptionContext.Exception == null || exceptionContext.ExceptionHandled)
                {
                    // We don't need to do anything to trigger a short circuit. If there's another
                    // exception filter on the stack it will check the same set of conditions
                    // and then just skip itself.
                    _logger.ExceptionFilterShortCircuited(filter);
                }

                goto case State.ExceptionEnd;
            }

            case State.ExceptionSyncBegin:
            {
                var task = InvokeNextExceptionFilterAsync();
                if (task.Status != TaskStatus.RanToCompletion)
                {
                    next = State.ExceptionSyncEnd;
                    return(task);
                }

                goto case State.ExceptionSyncEnd;
            }

            case State.ExceptionSyncEnd:
            {
                Debug.Assert(state != null);

                var filter           = (IExceptionFilter)state;
                var exceptionContext = _exceptionContext;

                // When we get here we're 'unwinding' the stack of exception filters. If we have an unhandled exception,
                // we'll call the filter. Otherwise there's nothing to do.
                if (exceptionContext?.Exception != null && !exceptionContext.ExceptionHandled)
                {
                    _diagnosticSource.BeforeOnException(exceptionContext, filter);
                    _logger.BeforeExecutingMethodOnFilter(
                        FilterTypeConstants.ExceptionFilter,
                        nameof(IExceptionFilter.OnException),
                        filter);

                    filter.OnException(exceptionContext);

                    _diagnosticSource.AfterOnException(exceptionContext, filter);
                    _logger.AfterExecutingMethodOnFilter(
                        FilterTypeConstants.ExceptionFilter,
                        nameof(IExceptionFilter.OnException),
                        filter);

                    if (exceptionContext.Exception == null || exceptionContext.ExceptionHandled)
                    {
                        // We don't need to do anything to trigger a short circuit. If there's another
                        // exception filter on the stack it will check the same set of conditions
                        // and then just skip itself.
                        _logger.ExceptionFilterShortCircuited(filter);
                    }
                }

                goto case State.ExceptionEnd;
            }

            case State.ExceptionInside:
            {
                goto case State.ActionBegin;
            }

            case State.ExceptionHandled:
            {
                // We arrive in this state when an exception happened, but was handled by exception filters
                // either by setting ExceptionHandled, or nulling out the Exception or setting a result
                // on the ExceptionContext.
                //
                // We need to execute the result (if any) and then exit gracefully which unwinding Resource
                // filters.

                Debug.Assert(state != null);
                Debug.Assert(_exceptionContext != null);

                if (_exceptionContext.Result == null)
                {
                    _exceptionContext.Result = new EmptyResult();
                }

                _result = _exceptionContext.Result;

                var task = InvokeAlwaysRunResultFilters();
                if (task.Status != TaskStatus.RanToCompletion)
                {
                    next = State.ResourceInsideEnd;
                    return(task);
                }

                goto case State.ResourceInsideEnd;
            }

            case State.ExceptionEnd:
            {
                var exceptionContext = _exceptionContext;

                if (scope == Scope.Exception)
                {
                    isCompleted = true;
                    return(Task.CompletedTask);
                }

                if (exceptionContext != null)
                {
                    if (exceptionContext.Result != null ||
                        exceptionContext.Exception == null ||
                        exceptionContext.ExceptionHandled)
                    {
                        goto case State.ExceptionHandled;
                    }

                    Rethrow(exceptionContext);
                    Debug.Fail("unreachable");
                }

                var task = InvokeResultFilters();
                if (task.Status != TaskStatus.RanToCompletion)
                {
                    next = State.ResourceInsideEnd;
                    return(task);
                }
                goto case State.ResourceInsideEnd;
            }

            case State.ActionBegin:
            {
                var task = InvokeInnerFilterAsync();
                if (task.Status != TaskStatus.RanToCompletion)
                {
                    next = State.ActionEnd;
                    return(task);
                }

                goto case State.ActionEnd;
            }

            case State.ActionEnd:
            {
                if (scope == Scope.Exception)
                {
                    // If we're inside an exception filter, let's allow those filters to 'unwind' before
                    // the result.
                    isCompleted = true;
                    return(Task.CompletedTask);
                }

                Debug.Assert(scope == Scope.Invoker || scope == Scope.Resource);
                var task = InvokeResultFilters();
                if (task.Status != TaskStatus.RanToCompletion)
                {
                    next = State.ResourceInsideEnd;
                    return(task);
                }
                goto case State.ResourceInsideEnd;
            }

            case State.ResourceInsideEnd:
            {
                if (scope == Scope.Resource)
                {
                    _resourceExecutedContext = new ResourceExecutedContext(_actionContext, _filters)
                    {
                        Result = _result,
                    };

                    goto case State.ResourceEnd;
                }

                goto case State.InvokeEnd;
            }

            case State.ResourceEnd:
            {
                if (scope == Scope.Resource)
                {
                    isCompleted = true;
                    return(Task.CompletedTask);
                }

                Debug.Assert(scope == Scope.Invoker);
                Rethrow(_resourceExecutedContext);

                goto case State.InvokeEnd;
            }

            case State.InvokeEnd:
            {
                isCompleted = true;
                return(Task.CompletedTask);
            }

            default:
                throw new InvalidOperationException();
            }
        }
コード例 #27
0
        //фильтр для ограничения доступа к сайту старых браузеров типа IE
        //В качестве параметра в оба метода передается параметр типа ResourceExecutedContext,
        //который позволяет получить данные запроса и управлять ответом.

        //срабатывает после выполнения метода и фильтров действий исключений и результатов
        public void OnResourceExecuted(ResourceExecutedContext context)
        {
            Console.WriteLine(" A1 - OnResourceExecuted");
        }
コード例 #28
0
    public async Task EndMiddleware_PropagatesFullExceptionInfo_ToEarlierMiddleware()
    {
        // Arrange
        var services               = new ServiceCollection();
        var appBuilder             = new ApplicationBuilder(services.BuildServiceProvider());
        var pipelineBuilderService = new MiddlewareFilterBuilder(new MiddlewareFilterConfigurationProvider())
        {
            ApplicationBuilder = appBuilder,
        };

        Pipeline1.ConfigurePipeline = ab =>
        {
            ab.Use((ctx, next) =>
            {
                return(next(ctx));
            });
        };

        var middlewareFilterFeature = new MiddlewareFilterFeature
        {
            ResourceExecutionDelegate = () =>
            {
                ExceptionDispatchInfo exceptionInfo;
                try
                {
                    // Create a small stack trace.
                    throw new InvalidOperationException("Error!!!");
                }
                catch (Exception ex)
                {
                    exceptionInfo = ExceptionDispatchInfo.Capture(ex);
                }

                var actionContext = new ActionContext(
                    new DefaultHttpContext(),
                    new RouteData(),
                    new ActionDescriptor(),
                    new ModelStateDictionary());
                var context = new ResourceExecutedContext(actionContext, new List <IFilterMetadata>())
                {
                    ExceptionDispatchInfo = exceptionInfo,
                };

                return(Task.FromResult(context));
            },
        };

        var features = new FeatureCollection();

        features.Set <IMiddlewareFilterFeature>(middlewareFilterFeature);
        var httpContext = new DefaultHttpContext(features);

        // Act
        var pipeline = pipelineBuilderService.GetPipeline(typeof(Pipeline1));

        // Assert
        Assert.NotNull(pipeline);

        var exception = await Assert.ThrowsAsync <InvalidOperationException>(() => pipeline(httpContext));

        Assert.Null(exception.InnerException);
        Assert.Equal("Error!!!", exception.Message);

        var stack = exception.StackTrace;

        Assert.Contains(typeof(MiddlewareFilterBuilder).FullName, stack);
        Assert.Contains(typeof(MiddlewareFilterBuilderTest).FullName, stack);
        Assert.Contains(nameof(EndMiddleware_PropagatesFullExceptionInfo_ToEarlierMiddleware), stack);
    }
コード例 #29
0
        private async Task InvokeResourceFilterAsync()
        {
            Debug.Assert(_resourceExecutingContext != null);

            var item = _cursor.GetNextFilter <IResourceFilter, IAsyncResourceFilter>();

            try
            {
                if (item.FilterAsync != null)
                {
                    _diagnosticSource.BeforeOnResourceExecution(_resourceExecutingContext, item.FilterAsync);

                    await item.FilterAsync.OnResourceExecutionAsync(_resourceExecutingContext, InvokeResourceFilterAwaitedAsync);

                    if (_resourceExecutedContext == null)
                    {
                        // If we get here then the filter didn't call 'next' indicating a short circuit
                        _resourceExecutedContext = new ResourceExecutedContext(_resourceExecutingContext, _filters)
                        {
                            Canceled = true,
                            Result   = _resourceExecutingContext.Result,
                        };
                    }

                    _diagnosticSource.AfterOnResourceExecution(_resourceExecutedContext, item.FilterAsync);

                    if (_resourceExecutingContext.Result != null)
                    {
                        _logger.ResourceFilterShortCircuited(item.FilterAsync);

                        await InvokeResultAsync(_resourceExecutingContext.Result);
                    }
                }
                else if (item.Filter != null)
                {
                    _diagnosticSource.BeforeOnResourceExecuting(_resourceExecutingContext, item.Filter);

                    item.Filter.OnResourceExecuting(_resourceExecutingContext);

                    _diagnosticSource.AfterOnResourceExecuting(_resourceExecutingContext, item.Filter);

                    if (_resourceExecutingContext.Result != null)
                    {
                        // Short-circuited by setting a result.
                        _logger.ResourceFilterShortCircuited(item.Filter);

                        await InvokeResultAsync(_resourceExecutingContext.Result);

                        _resourceExecutedContext = new ResourceExecutedContext(_resourceExecutingContext, _filters)
                        {
                            Canceled = true,
                            Result   = _resourceExecutingContext.Result,
                        };
                    }
                    else
                    {
                        await InvokeResourceFilterAsync();

                        Debug.Assert(_resourceExecutedContext != null);

                        _diagnosticSource.BeforeOnResourceExecuted(_resourceExecutedContext, item.Filter);

                        item.Filter.OnResourceExecuted(_resourceExecutedContext);

                        _diagnosticSource.AfterOnResourceExecuted(_resourceExecutedContext, item.Filter);
                    }
                }
                else
                {
                    // >> ExceptionFilters >> Model Binding >> ActionFilters >> Action
                    await InvokeAllExceptionFiltersAsync();

                    // If Exception Filters provide a result, it's a short-circuit due to an exception.
                    // We don't execute Result Filters around the result.
                    Debug.Assert(_exceptionContext != null);
                    if (_exceptionContext.Result != null)
                    {
                        // This means that exception filters returned a result to 'handle' an error.
                        // We're not interested in seeing the exception details since it was handled.
                        await InvokeResultAsync(_exceptionContext.Result);

                        _resourceExecutedContext = new ResourceExecutedContext(_resourceExecutingContext, _filters)
                        {
                            Result = _exceptionContext.Result,
                        };
                    }
                    else if (_exceptionContext.Exception != null && !_exceptionContext.ExceptionHandled)
                    {
                        // If we get here, this means that we have an unhandled exception.
                        // Exception filted didn't handle this, so send it on to resource filters.
                        _resourceExecutedContext = new ResourceExecutedContext(_resourceExecutingContext, _filters);

                        // Preserve the stack trace if possible.
                        _resourceExecutedContext.Exception = _exceptionContext.Exception;
                        if (_exceptionContext.ExceptionDispatchInfo != null)
                        {
                            _resourceExecutedContext.ExceptionDispatchInfo = _exceptionContext.ExceptionDispatchInfo;
                        }
                    }
                    else
                    {
                        // We have a successful 'result' from the action or an Action Filter, so run
                        // Result Filters.
                        Debug.Assert(_actionExecutedContext != null);
                        var result = _actionExecutedContext.Result;

                        // >> ResultFilters >> (Result)
                        await InvokeAllResultFiltersAsync(result);

                        _resourceExecutedContext = new ResourceExecutedContext(_resourceExecutingContext, _filters)
                        {
                            Result = _resultExecutedContext.Result,
                        };
                    }
                }
            }
            catch (Exception exception)
            {
                _resourceExecutedContext = new ResourceExecutedContext(_resourceExecutingContext, _filters)
                {
                    ExceptionDispatchInfo = ExceptionDispatchInfo.Capture(exception)
                };
            }

            Debug.Assert(_resourceExecutedContext != null);
        }
コード例 #30
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
 }
コード例 #31
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     Console.WriteLine($"--------------------Resource---------------------");
     Console.WriteLine($"***** {context.ActionDescriptor.DisplayName}  MyResourceFilter.OnResourceExecuted");
     Console.WriteLine($"-----------------------------------------------");
 }
コード例 #32
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     throw new NotImplementedException();
 }
コード例 #33
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
     _logger.Debug($"Executing IResourceFilter.OnResourceExecuted: cancelled {context.Canceled}");
 }
コード例 #34
0
 public void OnResourceExecuted(ResourceExecutedContext context)
 {
 }
コード例 #35
0
 /// <inheritdoc />
 public void OnResourceExecuted([NotNull] ResourceExecutedContext context)
 {
 }