Asp.net Core-过滤器
2021-05-01 14:29
标签:rri ajax tap mil lse source 系统 创建 header 11 ActionFilter: ResultFilter: ExceptionFilter: 未完待续... Asp.net Core-过滤器 标签:rri ajax tap mil lse source 系统 创建 header 原文地址:https://www.cnblogs.com/fanfan-90/p/12144471.htmlResourceFilter:
和ActionFilter的区别是:OnResourceExecuting在Controller创建之前调用public class CustomerResourceFilterAttribute : Attribute, IResourceFilter
{
private static ConcurrentDictionarystring, object> CACHE_DICT = new ConcurrentDictionarystring, object>();
private string _cacheKey;
public void OnResourceExecuting(ResourceExecutingContext context)
{
_cacheKey = context.HttpContext.Request.Path.ToString();
if (CACHE_DICT.TryGetValue(_cacheKey, out object result))
{
var actionResult = result as IActionResult;
if (actionResult != null)
{
context.Result = actionResult;
}
}
}
public void OnResourceExecuted(ResourceExecutedContext context)
{
if (!CACHE_DICT.ContainsKey(_cacheKey))
{
if (context.Result != null)
{
CACHE_DICT.TryAdd(_cacheKey, context.Result);
}
}
}
}
public class CustomerActionFilterAttribute : Attribute, IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
Console.WriteLine("OnActionExecuting");
}
public void OnActionExecuted(ActionExecutedContext context)
{
Console.WriteLine("OnActionExecuted");
}
}
public class CustomerResultFilterAttribute : Attribute, IResultFilter
{
public void OnResultExecuting(ResultExecutingContext context)
{
Console.WriteLine("OnResultExecuting");
}
public void OnResultExecuted(ResultExecutedContext context)
{
Console.WriteLine("OnResultExecuted");
}
}
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
private readonly IHostingEnvironment _hostingEnvironment;
private readonly IModelMetadataProvider _modelMetadataProvider;
public CustomExceptionFilterAttribute(
IHostingEnvironment hostingEnvironment,
IModelMetadataProvider modelMetadataProvider)
{
_hostingEnvironment = hostingEnvironment;
_modelMetadataProvider = modelMetadataProvider;
}
public override void OnException(ExceptionContext filterContext)
{
if (!filterContext.ExceptionHandled)//异常有没有被处理过
{
string controllerName = (string)filterContext.RouteData.Values["controller"];
string actionName = (string)filterContext.RouteData.Values["action"];
if (this.isAjaxRequest(filterContext.HttpContext.Request))//检查请求头
{
filterContext.Result = new JsonResult(
new AjaxResult()
{
Result = DoResult.Failed,
PromptMsg = "系统出现异常,请联系管理员",
DebugMessage = filterContext.Exception.Message
}//这个就是返回的结果
);
}
else
{
var result = new ViewResult { ViewName = "~/Views/Shared/Error.cshtml" };
result.ViewData = new ViewDataDictionary(_modelMetadataProvider, filterContext.ModelState);
result.ViewData.Add("Exception", filterContext.Exception);
filterContext.Result = result;
}
filterContext.ExceptionHandled = true;
}
}
private bool isAjaxRequest(HttpRequest request)
{
string header = request.Headers["X-Requested-With"];
return "XMLHttpRequest".Equals(header);
}
}
下一篇:01. MVC核心基础