Can I use the HttpContext.ApplicationInstance.Context
class to store session data using the Session
function?
Or there is a better way to do this?
问题:
回答1:
Normally the session is available as a property in your controller actions:
public ActionResult Index()
{
this.Session["foo"] = "bar";
return View();
}
Since the Session
property is of type HttpSessionStateBase
it can be more easily mocked in a unit test. Please never use the static HttpContext.Current.Session
as you might see suggested elsewhere.
If you are not inside a controller action you can access the session if you have an instance of HttpContextBase
(which is almost in every part of the MVC pipeline) using its Session property.
回答2:
Yes, you can apply data into a Session by utilizing the HttpContext
. You should be wary of such implementations though, Model View Controller is in nature stateless. The session though will dictate some form of state.
You'll have to account for that, otherwise you could potentially introduce a large quantity of orphaned session variables if they're not accounted for. Which could eat memory in your environment rapidly depending on your application.
If the application is small, you could easily do it with the following in your Controller:
HttpContext.Current.Session.Add("Title", "Data");