当我在动作上有CompressFilter并且它们是错误时,我没有得到我的ExceptionHandling命中.请求未返回任何响应.如果我删除压缩过滤器然后它返回错误数组就好了.如何在错误上跳过压缩过滤器,或者让它达到第二个?
控制器动作
[HttpPost,CompressAttribute] public virtual ActionResult Builder()
Global.asax中
GlobalConfiguration.Configuration.Filters.Add(new ExceptionHandlingAttribute());
CompressFilter
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,Inherited = true,AllowMultiple = true)] public class CompressAttribue : ActionFilterattribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { var encodingsAccepted = filterContext.HttpContext.Request.Headers["Accept-Encoding"]; if (string.IsNullOrEmpty(encodingsAccepted)) return; encodingsAccepted = encodingsAccepted.ToLowerInvariant(); var response = filterContext.HttpContext.Response; if (encodingsAccepted.Contains("gzip")) { response.AppendHeader("content-encoding","gzip"); response.Filter = new GZipStream(response.Filter,CompressionMode.Compress); } else if (encodingsAccepted.Contains("deflate")) { response.AppendHeader("content-encoding","deflate"); response.Filter = new DeflateStream(response.Filter,CompressionMode.Compress); } } }
解决方法
我将它移动到OnActionExecuted并且它有效,因为它包含Exception属性.
public override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); if (filterContext.Exception == null) { var encodingsAccepted = filterContext.HttpContext.Request.Headers["Accept-Encoding"]; if (!encodingsAccepted.IsBlank()) { encodingsAccepted = encodingsAccepted.ToLowerInvariant(); var response = filterContext.HttpContext.Response; if (encodingsAccepted.Contains("gzip")) { response.AppendHeader("content-encoding","gzip"); response.Filter = new GZipStream(response.Filter,CompressionMode.Compress); } else if (encodingsAccepted.Contains("deflate")) { response.AppendHeader("content-encoding","deflate"); response.Filter = new DeflateStream(response.Filter,CompressionMode.Compress); } } } }