Reputation: 4128
I'm trying to add value to the Session object in a Controller like this:
Request.HttpContext.Session.SetString("key, "value")
But I get the next error: The session cannot be established after the response has started.
How can I add a value to the Session object from a controller?
Thank you.
Edit:
This is the code:
public IActionResult SetValue()
{
Request.HttpContext.Session.SetString("user", "aam3");
return View();
}
Upvotes: 5
Views: 1281
Reputation: 4128
OK, I found the problem, I had a custom middleware before the App.UseMvc
statement, in that middleware I had the line await Context.Response.WriteAsync("Testing Middleware")
, that line inmedaitly started the response, for that reason I wasn't able to change the Session later in the controller.
Thank you.
Upvotes: 3
Reputation: 17485
Please try this. It is working for me and I am using CTP 6.
public IActionResult Index()
{
Context.Session.SetString("key", "value");
return View();
}
Also to be more sure it is important that what you have done in Startup.cs file.
Upvotes: 1