在视图

时间:2016-03-03 14:51:40

标签: c# html asp.net .net asp.net-mvc

代码取自Codeproject

主视图中使用 Html.action 呈现部分视图时,它在response.Filter上给出了值不能为null的异常。

过滤

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new CompressAttribute());
    }
}

public class CompressAttribute : 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("deflate"))
        {
            response.AppendHeader("Content-encoding", "deflate");
            response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
        }
        else if (encodingsAccepted.Contains("gzip"))
        {
            response.AppendHeader("Content-encoding", "gzip");
            response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
        }
    }
}

查看

<div>
   @Html.Action("GetAccountCompanies", "Account")
</div>

动作

[HttpGet]
[ChildActionOnly]
public PartialViewResult GetAccountCompanies()
{
     return PartialView("~/Views/Shared/_AccountCompanies.cshtml");
}

异常

response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
  

Response.Filter =值不能为空

我在评论时过滤

@Html.Action("GetAccountCompanies", "Account")

1 个答案:

答案 0 :(得分:0)

为每个操作调用CompressAttribute,因此我们需要确保不压缩子进程,(response.filter == null)

public class CompressAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var response = filterContext.HttpContext.Response;

        if (response.Filter != null)
        {
            var encodingsAccepted = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
            if (string.IsNullOrEmpty(encodingsAccepted)) return;

            encodingsAccepted = encodingsAccepted.ToLowerInvariant();

            if (encodingsAccepted.Contains("deflate"))
            {
                response.AppendHeader("Content-encoding", "deflate");
                response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
            }
            else if (encodingsAccepted.Contains("gzip"))
            {
                response.AppendHeader("Content-encoding", "gzip");
                response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
            }
        }
    }
}