示例
新建FeatureDisabledResourceFilter.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace CRUDExample.Filters.ResourceFilters
{
public class FeatureDisabledResourceFilter : IAsyncResourceFilter
{
private readonly ILogger<FeatureDisabledResourceFilter> _logger;
private readonly bool _isDisabled;
public FeatureDisabledResourceFilter(ILogger<FeatureDisabledResourceFilter> logger, bool isDisabled = true)
{
_logger = logger;
_isDisabled = isDisabled;
}
public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
{
//TO DO: before logic
_logger.LogInformation("{FilterName}.{MethodName} - before", nameof(FeatureDisabledResourceFilter), nameof(OnResourceExecutionAsync));
if (_isDisabled)
{
//context.Result = new NotFoundResult(); //404 - Note Found
context.Result = new StatusCodeResult(501); //501 - Not Implemented
}
else
{
await next();
// TO DO: after logic
_logger.LogInformation("{FilterName}.{MethodName} - after", nameof(FeatureDisabledResourceFilter), nameof(OnResourceExecutionAsync));
}
}
}
}
PersonsController.cs中添加TypeFilter
//处理Post请求
[Route("[action]")]
[HttpPost]
[TypeFilter(typeof(PersonCreateAndEditPostActionFilter))]
[TypeFilter(typeof(FeatureDisabledResourceFilter))]
public async Task<IActionResult> Create(PersonAddRequest personAddRequest)
执行程序点击Create后显示
PersonsController.cs中添加TypeFilter中添加false参数或者删除筛选器后,程序正常运行
//处理Post请求
[Route("[action]")]
[HttpPost]
[TypeFilter(typeof(PersonCreateAndEditPostActionFilter))]
[TypeFilter(typeof(FeatureDisabledResourceFilter), Arguments = new object[] {false})]
public async Task<IActionResult> Create(PersonAddRequest personAddRequest)
Gitee获取源码:
https://gitee.com/huang_jianhua0101/asp.-net-core-8.git
标签:TypeFilter,FeatureDisabledResourceFilter,isDisabled,Filter,Resource,logger,251,p From: https://blog.csdn.net/KevinHuang2088/article/details/139451344