MVC SessionStateAttribute not working as Global At

2019-04-08 03:19发布

问题:

How do you setup SessionStateAttribute as a global filter in MVC3? In my Global.asax I have this in the RegisterGlobalFilters method.

filters.Add(new SessionStateAttribute(SessionStateBehavior.Disabled));

And in my home controller I have this.

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";

        Session["Blend"] = "Will it blend?";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}

But for some reason it still lets me use the Session. However if I decorate the HomeController class itself with the attribute, I get an error on the line utilizing the Session about a Object reference being null, which I'm guessing is intended if the Session is never created?

I am starting to wonder if there is something wrong with my project. I've been getting little problems like this one with standard behavior that are supposed to just work.

Anyone else had problems with things like this?

回答1:

SessionStateAttribute is not an action filter, so you cannot add it as a global action filter. It's a special attribute which allows you to decorate your controllers with and have a more fine grained control over the session mode per controller.

To disable the session globally for the entire application put the following in your web.config:

<sessionState mode="Off" />