I bind the model to a session in ASP MVC Framework like this:
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
Cart cart = null;
if(controllerContext.HttpContext.Session != null)
{
cart = (Cart)controllerContext.HttpContext.Session[sessionKey];
}
if(cart == null)
{
cart = new Cart();
if (controllerContext.HttpContext.Session != null)
{
controllerContext.HttpContext.Session[sessionKey] = cart;
}
}
return cart;
}
Now I want to do the same thing in ASM MVC Core, and this was my attempt:
public Task BindModelAsync(ModelBindingContext bindingContext)
{
Cart cart = null;
if (bindingContext.HttpContext.Session != null)
{
cart = (Cart)JsonConvert.DeserializeObject(bindingContext.HttpContext.Session.GetString(sessionKey));
}
if (cart == null)
{
cart = new Cart();
if (bindingContext.HttpContext.Session != null)
{
bindingContext.HttpContext.Session.SetString(sessionKey, JsonConvert.SerializeObject(cart));
}
}
return Task.CompletedTask;
}
I also have the class for model binder provider.
But I get a run-time error on this line, saying that the object is null:
cart = (Cart)JsonConvert.DeserializeObject(bindingContext.HttpContext.Session.GetString(sessionKey));
The string returned from 'GetString(sessionKey)' is null. The full message is:
System.ArgumentNullException: 'Value cannot be null. Parameter name: value''.