我是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")
,这会删除错误,但不会告诉客户端实际重定向。
我尝试在网上搜索没有运气,而且我的解决能力已经结束了。任何人都可以指出我正确的方向,或建议更好地处理上面的一个或另一个吗?