Skip to content

Add Session Read only to backend calls #2505

Description

@geofranzi

will resolve: #2303

Remove Session Option:

 string cacheKey = $"Menu_{userName}";
            if (isAuthenticated && HttpContext.Cache[cacheKey] != null)
            {
                return Json((Menu)HttpContext.Cache[cacheKey], JsonRequestBehavior.AllowGet);
            }
 // set menu to cache if user is authenticated
            if (!string.IsNullOrEmpty(userName) && isAuthenticated)
            {
                // This expires exactly 20 minutes from now, no matter what
                HttpContext.Cache.Insert(
                    cacheKey,
                    menu,
                    null,
                    DateTime.Now.AddMinutes(20), // Absolute expiration set to 20 mins
                    System.Web.Caching.Cache.NoSlidingExpiration // Disable sliding expiration
);
            }

either: Step 1: Create the Factory


C#
public class ReadOnlySessionControllerFactory : DefaultControllerFactory
{
    protected override SessionStateBehavior GetControllerSessionBehavior(
        System.Web.Routing.RequestContext requestContext, 
        Type controllerType)
    {
        // Force EVERY controller to be Read-Only
        return SessionStateBehavior.ReadOnly;
    }
}
Step 2: Register it in Global.asax
Inside your Application_Start() method, tell MVC to use your new factory:

C#
protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);

    // Register the global read-only session factory here:
    ControllerBuilder.Current.SetControllerFactory(new ReadOnlySessionControllerFactory());
}

or better

[SessionState(SessionStateBehavior.ReadOnly)]
public class BaseController : Controller
{
    // Common logic can go here later
}

public class MenuController : BaseController
{
    // This is automatically ReadOnly because it inherits from BaseController
    public ActionResult GetMenu() { ... } 
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions