Как использовать переменную сеанса в MVC
Я объявил переменную Session в файле "Global.asax" как
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
int temp=4;
HttpContext.Current.Session.Add("_SessionCompany",temp);
}
И хочу использовать эту переменную сеанса в действии My Controller как,
public ActionResult Index()
{
var test = this.Session["_SessionCompany"];
return View();
}
Но я получаю исключение при доступе к переменной сеанса.
Пожалуйста, помогите мне в этом, как я могу получить доступ к переменной сеанса в действие моего контроллера.
Я получаю исключение вроде
"Object Reference not set to an Insatance of an object"
в Application_Start
в Global.asax на линии
HttpContext.Current.Session.Add("_SessionCompany",temp);
Ответы
Ответ 1
Нить, которая запускает приложение, не является потоком запроса, используемым, когда пользователь делает запрос на веб-страницу.
Это означает, что когда вы устанавливаете в Application_Start
, вы не устанавливаете его для какого-либо пользователя.
Вы хотите установить сеанс на событие Session_Start
.
Edit:
Добавьте новое событие в файл global.asax.cs с именем Session_Start
и удалите связанный с сеансом материал из Application_Start
protected void Session_Start(Object sender, EventArgs e)
{
int temp = 4;
HttpContext.Current.Session.Add("_SessionCompany",temp);
}
Это должно исправить вашу проблему.
Ответ 2
Вы не должны устанавливать переменные сеанса в Application_Start(), так как этот метод вызывается только один раз, когда приложение запускается в IIS. Это не сеанс.
Кроме того, я предполагаю, что ваш контроллер имеет свойство Session? Правильно ли вы установили его?
Используйте HttpContext.Current.Session["_SessionCompany"]
, а не this.Session["_SessionCompany"]
- это должно работать.
Ответ 3
В контроллере вы можете получить доступ так:
YourControllerID.ControllerContext.HttpContext.Session [ "_ SessionCompany" ]
Ответ 4
Используйте этот вспомогательный класс:
namespace Projectname.UI.HtmlHelpers
{
//[DebuggerNonUserCodeAttribute()]
public static class SessionHelper
{
public static T Get<T>(string index)
{
//this try-catch is done to avoid the issue where the report session is timing out and breaking the entire session on a refresh of the report
if (HttpContext.Current.Session == null)
{
var i = HttpContext.Current.Session.Count - 1;
while (i >= 0)
{
try
{
var obj = HttpContext.Current.Session[i];
if (obj != null && obj.GetType().ToString() == "Microsoft.Reporting.WebForms.ReportHierarchy")
HttpContext.Current.Session.RemoveAt(i);
}
catch (Exception)
{
HttpContext.Current.Session.RemoveAt(i);
}
i--;
}
if (!HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.Equals("~/Home/Default"))
{
HttpContext.Current.Response.Redirect("~/Home/Default");
}
throw new System.ComponentModel.DataAnnotations.ValidationException(string.Format("You session has expired or you are currently logged out.", index));
}
try
{
if (HttpContext.Current.Session.Keys.Count > 0 && !HttpContext.Current.Session.Keys.Equals(index))
{
return (T)HttpContext.Current.Session[index];
}
else
{
var i = HttpContext.Current.Session.Count - 1;
while (i >= 0)
{
try
{
var obj = HttpContext.Current.Session[i];
if (obj != null && obj.GetType().ToString() == "Microsoft.Reporting.WebForms.ReportHierarchy")
HttpContext.Current.Session.RemoveAt(i);
}
catch (Exception)
{
HttpContext.Current.Session.RemoveAt(i);
}
i--;
}
if (!HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.Equals("~/Home/Default"))
{
HttpContext.Current.Response.Redirect("~/Home/Default");
}
throw new System.ComponentModel.DataAnnotations.ValidationException(string.Format("You session does not contain {0} or has expired or you are currently logged out.", index));
}
}
catch (Exception e)
{
var i = HttpContext.Current.Session.Count - 1;
while (i >= 0)
{
try
{
var obj = HttpContext.Current.Session[i];
if (obj != null && obj.GetType().ToString() == "Microsoft.Reporting.WebForms.ReportHierarchy")
HttpContext.Current.Session.RemoveAt(i);
}
catch (Exception)
{
HttpContext.Current.Session.RemoveAt(i);
}
i--;
}
if (!HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.Equals("~/Home/Default"))
{
HttpContext.Current.Response.Redirect("~/Home/Default");
}
return default(T);
}
}
public static void Set<T>(string index, T value)
{
HttpContext.Current.Session[index] = (T)value;
}
}
}
и в вашем контроллере вы установите все, например. контроллер входа:
Session Helper.Set<string>("Username", Login User.User Name);
Session Helper.Set<int?>("Tenant Id", Login User.Tenant Id);
SessionHelper.Set<User Type>("User Type");
SessionHelper.Set<string>("", Login User To String());
SessionHelper.Set<int>("Login User Id", Login User.Login UserId);
SessionHelper.Set<string>("Login User", Login User.To String());
SessionHelper.Set<string>("Tenant", Tenant);
SessionHelper.Set<string>("First name", Login User.First Name);
SessionHelper.Set<string>("Surname", Login User.Surname);
SessionHelper.Set<string>("Vendor ", Vendor );
SessionHelper.Set<string>("Wholesaler ", Wholesaler );
SessionHelper.Set<int?>("Vendor Id", Login User );
SessionHelper.Set<int?>("Wholesaler Id", Login User Wholesaler Id);
и вы просто вызываете его в любом месте:
var CreatedBy = SessionHelper.Get<int>("LoginUserId"),
это простой доступ к объекту или его назначение.
Ответ 5
public ActionResult DeclareSession()
{
int id=3;
Session["User"]=id;
int iUserID =Convert.ToInt32(HttpContext.Current.Session["User"].toString());
return true;
}