问题
I've been reading PRO ASP.NET MVC2 by Steven Sanderson and I still can't figure out something about session. In the book he tells how to develop a Cart based on session using a Custom model binder for session persisting. Everything works fine but I can't figure out how it really works under the hood. Since it's a fair amount of code I'll write a simplified version
Counter
public class Counter
{
public int counter = 0;
public void Increment(){
counter++;
}
}
CounterController
public ActionResult Index(Counter counter)
{
counter.Increment();
return View(counter);
}
CounterCustomModelBinder
public class CounterCustomModelBinder: IModelBinder
{
private const string counterSessionKey = "_counter";
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
Counter counter = (Counter)controllerContext.HttpContext.Session[counterSessionKey];
if (counter == null)
{
counter = new Counter();
controllerContext.HttpContext.Session[counterSessionKey] = counter;
}
return counter;
}
}
Global.asax
...
ModelBinders.Binders.Add(typeof(Counter), new CounterCustomModelBinder());
As you see there's a statement for fetching the session contents Counter counter = (Counter)controllerContext.HttpContext.Session[counterSessionKey]; But there's no statement for SAVING into session. I would expect the subsequent statement somewhere: controllerContext.HttpContext.Session[counterSessionKey] = counter; But this code doesn't appear anywhere
Nevertheless it still works. Somehow when updating the Counter object, the session gets updated Automagically... But I can't understand where when and HOW. Thanks to anyone will reply.
回答1:
The counter object is a class (reference type), and so the value that is already in the Session object is referenced by the the counter variable. See http://www.albahari.com/valuevsreftypes.aspx.
When you update the values in the counter object, you are updating them in the copy that already exists in the Session.
Note that this will probably not work if you use a Session server or a SQL Session server, as they do different things with Session. Right now, you are using a single, live collection of Session values, which is why it works at all. The object is being kept alive in ASP.NET's process between requests.
来源:https://stackoverflow.com/questions/6165241/asp-net-mvc-session