0

我对 MVC4 相当陌生。我有一个从服务器到客户端交换大量数据的应用程序。所有方法都通过 jQuery AJAX 调用执行。为了降低时间/带宽,我实现了一个自定义属性来处理我的控制器方法上的压缩:

public class CompressFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpRequestBase request = filterContext.HttpContext.Request;

        string acceptEncoding = request.Headers["Accept-Encoding"];

        if (string.IsNullOrEmpty(acceptEncoding)) return;

        acceptEncoding = acceptEncoding.ToUpperInvariant();

        HttpResponseBase response = filterContext.HttpContext.Response;

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

相当标准,工作正常。但是,我现在还尝试添加一个自定义属性来检查会话是否仍然存在,如果不存在则重定向到登录页面(通过注销功能)。第二个属性如下:

public class SessionExpireFilter : ActionFilterAttribute {

    public override void OnActionExecuting( ActionExecutingContext filterContext )
    {
        HttpContext ctx = HttpContext.Current;

        // check if session is supported
        if ( ctx.Session != null ) {

            // check if a new session id was generated
            if ( ctx.Session.IsNewSession ) {

                // If it says it is a new session, but an existing cookie exists, then it must
                // have timed out
                string sessionCookie = ctx.Request.Headers[ "Cookie" ];
                if ( ( null != sessionCookie ) && ( sessionCookie.IndexOf ( "ASP.NET_SessionId" ) >= 0 ) ) {

                    ctx.Response.Redirect ( "~/Home/Logout" );
                    //filterContext.Result = new RedirectResult("~/Home/Logout");
                }
            }
        }

        base.OnActionExecuting ( filterContext );
    }
}

问题是这会产生以下错误:

“发送 HTTP 标头后,服务器无法附加标头。”

我试过用 替换ctx.Response.Redirect......filterContext.Result = new RedirectResult("~/Home/Logout")这消除了错误,但没有告诉客户端实际重定向。

我试过在网上搜索但没有运气,我已经无法解决了。谁能指出我正确的方向,或者建议一种更好的方法来处理上述一个或另一个?

4

0 回答 0