开发者

ASP.Net MVC disable browser caching (firefox)

In my asp.net mvc project when a logged in user logs out and presses back button they are being able to back to the page and access data which needs you to be logged in.

I have already added this page to default page:

    HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHis开发者_开发知识库tory(false);
    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    HttpContext.Current.Response.Cache.SetNoStore();
    Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
    Response.Cache.SetValidUntilExpires(true);

This is my call to logout controller:

Welcome <b><%= Html.Encode(Page.User.Identity.Name)%></b>!
        <%--    [ <%= Html.ActionLink("Logout", "Logout", "Home")%> ]        --%> 
                <a href="#" onclick="Javascript:DisableHistory()"> Logout</a>

 function DisableHistory() {
            alert("testing123");
            window.history.forward(1);
            window.location = "http://localhost/test.web/Home.aspx/Logout";

        }



        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");

        }

THis happens only in firefox. How can I avoid it from caching that page.


The proper way is to return response headers and not to modify the HTML page.

Create a new attribute:

public class DisableCacheAttribute: ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RequestContext.HttpContext.Response.AddHeader("Pragma", "no-cache");
        filterContext.RequestContext.HttpContext.Response.AddHeader("Expires", "-1");
        filterContext.RequestContext.HttpContext.Response.AddHeader("Cache-Control", "no-cache, no-store");
        base.OnActionExecuting(filterContext);
    }
}

and use it on your actions:

[DisableCache]
public ActionResult YourMethod()
{
    return new Content("This is not cached");
}

This attribute will also work with IE which has a more aggressive caching.


Please set the header for FireFox

context.Response.Headers.Add("Cache-Control", "no-cache");
context.Response.Headers.Add("PRAGMA", "no-cache");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜