Cookie does not work in asp.net - asp.net

I have two pages, test1.aspx and test2.aspx
test1.aspx has this
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("test", "test");
cookie.Expires = DateTime.Now.AddDays(1);
Response.SetCookie(cookie);
}
test2.aspx has this
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Response.Cookies["test"].Value);
}
The value of the cookie is null, no matter how many times I tried. I tried to open page1 and then page 2, expecting a cookie to work, but it is not working, I don't know why.

I think you need to read off the Request instead of the response.
As MSDN suggestions
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Request.Cookies["test"].Value);
}
In a web application, the request comes from the client (browser) and the response is sent from the server. When validating cookies or cookie data from the browser you should use the Request.Cookies collection. When you are constructing cookies to be sent to the browser you need to add them to the Response.Cookies collection.
Additional thoughts on the use of SetCookie
Interestingly for HttpResponse.SetCookie as used on your first page; MSDN says this method is not intended for use in your code.
This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.
Even the example code found on this page uses the Response.Cookies.Add(MyCookie) approach and does not call SetCookie

You need is :
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(Request.Cookies["test"].Value);
}
There is a sample here:
Reading and Writing Cookies in ASP.NET and C#
Regards

Save cookie with (response) and read cookie by (request)
//write
response.cookies("abc") = 123;
//read
if ((request.cookies("abc") != null)) {
string abc = request.cookies("abc");
}

Use Response.Cookies.Add(cookie);
Reference: http://msdn.microsoft.com/en-us/library/system.web.httpresponse.cookies

On page test2.aspx
You should try this
protected void Page_Load(object sender, EventArgs e)
{
var httpCookie = Request.Cookies["test"];
if (httpCookie != null)
{
Response.Write(httpCookie.Value);
}
}

Related

Sending values from one page to another using sessions

I am sending values from send page to receive page using sessions, its working fine but the problem is I remember the URL and i directly run receive page its shows previous information but it's invalid is it....?
If end user directly visit receive page i need to restrict or give some message something like that
How can i overcome this problem..............
This is my code
send.aspx.cs
protected void gv_rowcommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow grow = (GridViewRow)(((LinkButton)e.CommandSource)).NamingContainer;
Session["c"] = grow.Cells[0].Text;
Session["s"] = grow.Cells[1].Text;
Session["e"] = grow.Cells[2].Text;
Session["t"] = grow.Cells[3].Text;
Session["a"] = grow.Cells[4].Text;
Response.Redirect("confirmation.aspx");
}
}
confirmation.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
lblgetcourse.Text = Convert.ToString(Session["c"]);
lblgetstartdate.Text = Convert.ToString(Session["s"]);
lblgetenddate.Text = Convert.ToString(Session["e"]);
lblgettimings.Text = Convert.ToString(Session["t"]);
lblgetamount.Text = Convert.ToString(Session["a"]);
}
Once you have displayed the values on the confirmation page you could remove them from the Session.
Session.Remove("c");
...
This will ensure that the confirmation page will always display fresh values coming from the send.aspx page. You could also check for the presence of those values in the session before displaying them.
On Confirmation Page, Fetch the Values from Session Variables an display them , then Clear Session variables just like: Session.Clear();
You can check the referrer header :
Request.UrlReferrer
and see where the request comes from.
so your page_load will look like :
protected void Page_Load(object sender, EventArgs e)
{
if (!Request.UrlReferrer=='...') Response.Redirect("~/login.aspx");
...
protected void Page_Load(object sender, EventArgs e)
{
if(Request.UrlReferrer.AbsolutePath == "~/send.aspx")
{
lblgetcourse.Text = Convert.ToString(Session["c"]);
lblgetstartdate.Text = Convert.ToString(Session["s"]);
lblgetenddate.Text = Convert.ToString(Session["e"]);
lblgettimings.Text = Convert.ToString(Session["t"]);
lblgetamount.Text = Convert.ToString(Session["a"]);
}
else
{
//do something
}
}

asp.net tracking user info

How is the best way to track user information, sesssion Id, cookies? once for user session.
In Default.aspx:
protected void Page_Load(object sender, EventArgs e)
{
IF (!isPostPack)
{
var sessionValue= System.Web.HttpContext.Current.Request.Cookies["ASP.NET_SessionId"] != null ? System.Web.HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value : string.Empty;
cONSOLE.WRITELINE(sessionValue);
}
}
This is not optimize. is there anyway to get only once the session iD,per user?
var sessionValue = System.Web.HttpContext.Current.Request.Cookies["ASP.NET_SessionId"]
!= null ?
System.Web.HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value : string.Empty;
All that will give you is the identifier that ASP.Net uses to track the session. This is rarely something you need to directly access in code.
But assuming that is what you want, it will be extremely fast. To make it cleaner, you can:
Access Request directly (no need for HttpContext inside a Page)
Store the value in a class-level variable that will live for the lifecycle of the page.
private string _sessionId;
protected void Page_Load(object sender, EventArgs e)
{
_sessionId = Request.Cookies["ASP.NET_SessionId"] != null
Request.Cookies["ASP.NET_SessionId"].Value : string.Empty;
}
If you want to do this only once per session (per the comments):
protected void Session_Start( object sender, EventArgs e )
{
using( var writer = File.CreateText( #"c:\temp\session-id.txt" ) )
{
writer.WriteLine( Session.SessionID );
}
}

Intercepting asp.net ajax webmethod

Is there a way to intercept asp.net ajax webmethods(aspx page static methods)?
i want to intercept before request reaching the method and also after sending the response.
use in global.asax file
protected void Application_BeginRequest(Object sender, EventArgs e)
{
//before method colling
string ss = HttpContext.Current.Request.Url.ToString();//use if it is equal to your page webmethod url i.e. domain.com/dfault.aspx/GetMessage;
if(ss=="http://domain.com/dfault.aspx/GetMessage")
{
do your work here
}
}
protected void Application_EndRequest(Object sender, EventArgs e)
{
//after method colling
string ss = HttpContext.Current.Request.Url.ToString();// use if it is equal to your page webmethod i.e. domain.com/dfault.aspx/GetMessage;;
if(ss=="http://domain.com/dfault.aspx/GetMessage")
{
do your work here
}
}
you can try fiddler or HTTtamper.

WCF\ASP.NET interoperability

I have a server application written in WCF using asynchronous callbacks, and a webforms application in ASP.NET.
All of the communication is fine between the 2 applications, I can call the exposed functions in the server via the web application, and the server can send callbacks to the web application, however sometimes the functions within the callback work, and other times, they don't.
For example, I would like a login button on the web app to send a username and password to the server, the server checks this against the database, and if the login information is correct, it should send a callback, which opens a new page in the web app.
Here is the relevant server code:
public void Login(String username, String password)
{
//DoCheckAgainstDatabase(username, password);
ICallback callback = OperationContext.Current.GetCallbackChannel<ICallback>();
callback.LoginSuccess();
}
and the web application code:
private InstanceContext _instanceContext;
private ServiceClient _service;
public CallbackHandler MyCallbackHandler = new CallbackHandler();
protected void Page_Load(object sender, EventArgs e)
{
_instanceContext = new InstanceContext(MyCallbackHandler);
_backEnd = new ServiceClient(_instanceContext, "NetTcpBinding_IAU", "net.tcp://localhost/MyService/Service");
_backEnd.Open();
MyCallbackHandler.LoginSucceeded += OnLoginSucceeded;
}
protected void LoginButton_Click(object sender, EventArgs e)
{
_backEnd.Login(UsernameTextBox.Text, PasswordTextBox.Text);
}
private void OnLoginSucceeded(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "OpenClientWindow", "window.open('Client.aspx','_self');", true);
}
I can put in breakpoints, and see that everything is working fine, it's just that the code 'ScriptManager.RegisterStartupScript...' does not execute properly all the time.
Could this be something to do with threading? Could anyone suggest a way to fix this please?
Thanks in advance!
David
It occurs to me that it's possible your page life cycle may be ending - or at least getting to the Render stage, which is where the start up script would be written to the output - before the callback is called.
Is it possible to call your service synchronously, and not proceed out of LoginButton_Click until the service call returns?
I think you are missing script tag - wrap your window.oppen with it, like
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "OpenClientWindow", "<script>window.open('Client.aspx','_self');</script>", true);
Thank you Ann L. for guidance on this. I have added a ManualResetEvent, and then in the button click method, I wait until I have received the callback, then proceed with opening the new page:
private InstanceContext _instanceContext;
private ServiceClient _service;
public CallbackHandler MyCallbackHandler = new CallbackHandler();
private ManualResetEvent _resetEvent = new ManualResetEvent(false);
protected void Page_Load(object sender, EventArgs e)
{
_instanceContext = new InstanceContext(MyCallbackHandler);
_backEnd = new ServiceClient(_instanceContext, "NetTcpBinding_IAU", "net.tcp://localhost/MyService/Service");
_backEnd.Open();
MyCallbackHandler.LoginSucceeded += OnLoginSucceeded;
}
protected void LoginButton_Click(object sender, EventArgs e)
{
_backEnd.Login(UsernameTextBox.Text, PasswordTextBox.Text);
_resetEvent.WaitOne();
ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "OpenClientWindow", "window.open('Client.aspx','_self');", true);
}
private void OnLoginSucceeded(object sender, EventArgs e)
{
_resetEvent.Set();
}

Asp.NET cookies returning null

I'm trying to save a cookie when a button is clicked like so...
protected void btn_login_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("test");
cookie["work"] = "now";
cookie.Expires = DateTime.Now + new TimeSpan(1, 0, 0, 0);
cookie.Domain = ".cookie.com";
Response.Cookies.Add(cookie);
}
Then on the page_load I am reading the cookie...
protected void Page_Load(object sender, EventArgs e)
{
string a = Response.Cookies["test"]["work"];
}
But it keeps coming back null. I am running this under localhost and I read that cookies won't save under localhost so I edited my host file to say
127.0.0.1 test.cookie.com
When I used Fiddler to see what was getting posted to the header of the page. It looks like this...
test/work = now
test =
So I can see that it is getting set but for some reason when I read it in it returns null.
On the page_load change it from Response.Cookies to Request.Cookies.
The Response object is for sending data back. The Request object has data that is passed to you.
example:
String a = Request.Cookies["test"]["work"];
Note that if the cookie doesn't exist, then this will cause a null reference exception.
Usually you should do something like:
protected void Page_Load(object sender, EventArgs e) {
HttpCookie cookie = Request.Cookies["test"];
String a = String.Empty;
if (cookie != null) {
a = cookie["work"];
}
}
Try this
Response.Cookies["work"].Value = "Value1"
Refer this for more information.
On pageload for reading the cookie try
string value = Request.Cookies["work"].Value

Resources