I have an ASP.NET application and dll which extends IHttpModule. I have used the below method to save the session variables in httpcontext through
public class Handler : IHttpModule,IRequiresSessionState
{
public void Init(HttpApplication httpApp)
{
httpApp.PreRequestHandlerExecute += new EventHandler(PreRequestHandlerExecute);
}
public void PreRequestHandlerExecute(object sender, EventArgs e)
{
var context = ((HttpApplication)sender).Context;
context.Session["myvariable"] = "Gowtham";
}
}
and in my asp.net Default.aspx page I have used code to retrive value as
public partial class _Default : System.Web.UI.Page, IRequiresSessionState
{
protected void Page_Load(object sender, EventArgs e)
{
String token = Context.Session["myvariable"].ToString();
}
}
I am getting error response as
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
In order to ensure whether the variables store in session I have crossed check by following method in class handler after storing the value in session as
string ss = context.Session["myvariable"].ToString();
it well executed and retrieved the value from session.
Why do you need to use Context and not Session directly? From the code I can only assume that you are going to set a value in the Session, and then read the value on page load. Rather than you do something like that, you can do this:
Add a Global Application Class, Right click on your project, Add > New Item, choose Global Application Class, and on that file, insert the following code to initialize the value
protected void Session_Start(object sender, EventArgs e)
{
Session["myvariable"] = "Gowtham";
}
On the Page_Load, you can access by:
if ( Session["myvariable"] != null ) {
String token = Context.Session["myvariable"].ToString();
}
Hope this help..
use System.Web.HttpContext.Current.Session["myvariable"] in both parts
Related
Quick Question...
In MVC5, are variables in the Global.asax accessible via all sessions or does MVC create and instance of Global for each session?
Example
public class Global : System.Web.HttpApplication
{
public static string Current_UserName = "";
protected void Session_Start(object sender, EventArgs e)
{
Current_UserName = User.Identity.Name;
}
}
So would user A Current_UserName change when user B loads the application?
Current_UserName would essentially be the last user that initialized their session. So user B who accesses the app after user A would show "B" in the static variable.
As Current_UserName user is static, the last assigned user will remain in that variable. I mean, the last session initiated user.
I am trying to retrieve some data from db and store it some Session variable in order to have it in _Layout.cshtml on all pages, no matter what page the user will access from the start.
Global.asax:
protected void Application_Start()
{
...
Manager mng = new Manager();
HttpContext.Current.Session["company-cellphone"] = mng.GetContacts().CompanyCellphone;
}
Error: Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
you are trying to access the session from Application_Start but there is no live Session yet.
session is not available in all events of global.asax
as a workaround try this:
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
{
HttpContext context = HttpContext.Current;
...
Manager mng = new Manager();
HttpContext.Current.Session["company-cellphone"] = mng.GetContacts().CompanyCellphone;
}
}
I'm not sure about your requirement but I would recommend to access the session in controller.initialize method
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
base.Initialize(requestContext);
//// access session here
requestContext.HttpContext.Session["company-cellphone"]=mng.GetContacts().CompanyCellphone;
}
Application_Start runs before any sessions can be created. And a session is specific to a single client connecting to your application.
You can create a static class and store the company-cellphone value in it.
In your Models folder create a new class file named Global.cs in that file create a static class with properties that will hold your application level information.
public static class Global
{
static string companyCellPhone;
public static string companyCellPhone
{
get
{
return this.companyCellPhone;
}
set
{
this.companyCellPhone= value;
}
}
Then your Application_Start method would look something like this:
protected void Application_Start()
{
...
Manager mng = new Manager();
Global.companyCellPhone = mng.GetContacts().CompanyCellphone;
}
I'm going to go out on a limb and guess that this is a single global value to be viewed by all users. In that case you could store the value in HttpApplicationState rather than HttpSessionState:
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
Application["YourValue"] = "SomeValue";
}
}
I'm not necessarily advocating its use. But just as Session can store user-specific values, Application stores values that are global to the application.
I prepared a very simple Web site to demonstrate this behavior.
It has one page with one Button and the following code:
public partial class TestStatic : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Class1.SetValue();
Label1.Text = Class1.st.ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = Class1.st.ToString();
}
}
and one class:
public class Class1
{
public Class1()
{
}
public static int st = 0;
public static void SetValue()
{
st = 1;
}
}
So when the page is loaded you see in Label1 that st=1. If user clicks on the Buttton that sometimes you can see st=0 and sometimes st=1. In debugging I see that sometimes command
public static int st = 0;
is executed when an user clicks on the Button and this is a reason why st is changed to zero. This behavior I can reproduce in framework 4.5 only: it does not occur in framework 3.5. Can somebody explain me such behavior?
Static data lives per application domain instance. Since the hosting (IIS) can unload application domains between web site calls, static data can be lost.
So, you really shouldn't rely on static in web apps.
static values are shared across all instances of a class inside of a single App Domain.
If you're using IIS Express, your appdomain may be getting recycled more often than you think it is.
reference this: Lifetime of ASP.NET Static Variable
I'm having an issue with ASP.NET's session variables and a web service proxy object. I can access any data I create inside the actual .asmx file, but adding data "Through" the session variable results in absolutely nothing happening.
My goal is quite simple, I want to create an "Almost Shopping cart". The customer enters a title into this text box, and it's sent to the Web Service. The web service is called in the masterpage, and it grabs an array list full of the "titles" that the customer is requesting.
The data is visible in a drop down box, and a label that stores the total cost of all the items (I'm not worried about the cost at the moment).
The issue is, anytime I call a web service method, absolutely nothing happens.
The Code in question:
Basket.asmx
public class basket : System.Web.Services.WebService {
ArrayList reservations = new ArrayList();
double total = 0;
public basket()
{
reservations.Add("Extreme Test Data");
reservations.Add("Moar Test Data");
}
[WebMethod]
public string[] getReservations()
{
//This may be part of the issue, still not sure.
return (string[])reservations.ToArray(typeof( string));
}
[WebMethod]
public string toString()
{
return reservations[reservations.Count - 1].ToString();
}
[WebMethod]
public double getTotal()
{
return total;
}
[WebMethod]
public void addCost(double price)
{
total = total + price;
}
[WebMethod]
public void addReservation(String title)
{
reservations.Add(title);
}
[WebMethod]
public void removeReservation(string title)
{
}
[WebMethod]
public int getLength()
{
return reservations.Count;
}
Global.asax
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
localhost.basket proxy = new localhost.basket();
Session["reservations"] = proxy;
}
(Everything else in global.asax is default)
Masterpage
This is the only relevant code in the masterpage, It calls the web service through the session variable.
protected void Page_Load(object sender, EventArgs e)
{
localhost.basket proxy = (localhost.basket)Session["reservations"];
lblTotal.Text = proxy.getTotal().ToString("c");
string[] res = proxy.getReservations();
ddReservations.DataSource = res;
ddReservations.DataBind();
proxy.addReservation("Half Life 2");
}
Reservations.aspx
This page submits the actual "new" data to the web service. I've cut out a lot of this (It's a group project, so there's a lot of code I didn't write).
protected void Page_Load(object sender, EventArgs e)
{
proxy = (localhost.basket)Session["reservations"];
Response.Write(proxy.toString() + "Count: " + proxy.getLength());
}
protected void cmdSubmit_Click(object sender, EventArgs e)
{
proxy.addReservation(txtGameTitle.Text);
proxy.addCost(39.99);
}
What does work: The default test values I entered in the ASMX, they load fine into the textbox.
So in short, can I use a web service proxy object in a session variable? If not, whats the best way to "share" this object?
Also: I'm using VS2005.
Thanks for any help!
Every web service call occurs on a different instance of the web service class. Your reservations variable cannot be used to maintain state between calls, since it's an instance variable.
You're better off making your service be stateless. However, for a case like this, you should store the shopping cart into a database. That way, the cart won't be lost on a system failure.
Is it possible to access SessionState in the Error event handler of a HttpModule following a 404?
Im trying to implement a consistent error handling mechanism for both full and partial postbacks using the technique described in this blog post,
ASP.NET Error Handling......
Instead of passing loads of parameters on the query string im trying to push the exception into session state and access it from the error page.
SessionState is never available at point I do my Server.Transfer (in error handler of HttpModule) so not available to error page.
Ive tried the trick of resetting the IHttpHandler to one with the IRequestSessionState interface but no joy.
Thanks in advance,
EDIT - The code of the IHttpModule error handler is,
void context_Error(object sender, EventArgs e)
{
try
{
var srcPageUrl = HttpContext.Current.Request.Url.ToString();
// If the error comes our handler we retrieve the query string
if (srcPageUrl.Contains(NO_PAGE_STR))
{
// Deliberate 404 from page error handler so transfer to error page
// SESSION NOT AVAILABLE !!!!
HttpContext.Current.ClearError();
HttpContext.Current.Server.Transfer(string.Format("{0}?ErrorKey={1}", ERROR_PAGE_URL, errorKey), true);
}
else
HttpContext.Current.Server.ClearError();
return;
}
catch (Exception ex)
{
Logging.LogEvent(ex);
}
}
Matt
public class ExceptionModule : IHttpModule
{
#region IHttpModule Members
public void Dispose()
{
}
/// <summary>
/// Init method to register the event handlers for
/// the HttpApplication
/// </summary>
/// <param name="application">Http Application object</param>
public void Init(HttpApplication application)
{
application.Error += this.Application_Error;
}
private void Application_Error(object sender, EventArgs e)
{
// Create HttpApplication and HttpContext objects to access
// request and response properties.
var application = (HttpApplication)sender;
var context = application.Context;
application.Session["errorData"] = "yes there is an error";
context.Server.Transfer("Error.aspx");
}
}
This should do the trick! works for me!