Request Cookies in .net - asp.net

I need to read with Request the value of cookie in .net page.
This cookie is created with Response before with asp classic 3.
I tried in asp classic 3:
<%
Response.Write(Request.Cookies("PRBT"))
%>
and the cookie is valorized and output is correct.
But if i try in the .net page the cookie value in debug is null, why?
My code below.
Any help would be appreciated, thanks in advance.
using System.Web;
HttpCookie PRBT;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PRBT = Request.Cookies["PRBT"];
if (HttpContext.Current.Request.Cookies["PRBT"] != null)
{
Response.Write("<p>" + PRBT.ToString());
}
}
}
EDIT 1
using System.Web;
HttpCookie PRBT;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PRBT = new HttpCookie("PRBT");
PRBT = Request.Cookies["PRBT"];
if (HttpContext.Current.Request.Cookies["PRBT"] != null)
{
Response.Write("<p>" + Server.UrlDecode(PRBT.ToString()));
}
}
}

To add a cookies you should use
HttpCookie cookie=HttpCookie("MyCookie", "MyValue")
Response.Cookies.Add(cookie);
More detail about cookies
http://www.codeproject.com/Articles/244904/Cookies-in-ASP-NET

Related

User.Identity.Name = "" but user is authenticated. possible?

protected void Page_Load(object sender, EventArgs e)
{
if (!User.Identity.IsAuthenticated)
{
Response.Redirect("~/login.aspx?ReturnUrl=userLevel.aspx");
}
if (!IsPostBack)
{
if (Request.Form["action"] == "getUserData")
{
string nm = User.Identity.Name;
Response.Clear();
Response.Write(nm);
Response.End();
}
}
}
the user loged in and he is authenticated, but when I check for his name I get ""
I try to get the user name using a jquery ajax, and I return the data to the ajax
update:
a look at my immediate window (while in a break point) when a user named moria is logedin
**User.Identity**
{System.Web.Security.FormsIdentity}
[System.Web.Security.FormsIdentity]: {System.Web.Security.FormsIdentity}
AuthenticationType: "Forms"
**IsAuthenticated: true**
**Name: ""**
**Membership.GetUser()**
**null**
**Membership.GetUser("moria")**
{moria}
Comment: null
CreationDate: {23/02/2016 01:10:08}
Email: "orders.gca#gmail.com"
IsApproved: true
IsLockedOut: false
IsOnline: false
LastActivityDate: {24/02/2016 03:21:08}
LastLockoutDate: {01/01/1754 02:00:00}
LastLoginDate: {24/02/2016 03:21:08}
LastPasswordChangedDate: {23/02/2016 01:10:08}
PasswordQuestion: "1"
ProviderName: "MySqlMembershipProvider"
ProviderUserKey: {ff589472-e852-4049-8803-6d22740414ee}
UserName: "moria"
Taking from ADreNaLiNe-DJ's answer and adding in the ability to redirect back to the calling page, you would add this to the Global.asax file:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
var loginUrl = new UrlHelper(HttpContext.Current.Request.RequestContext).Action("Login", "Account") ?? "";
if (!this.Request.IsAuthenticated && !this.Request.Path.Contains(loginUrl))
{
Response.Redirect(loginUrl + "?ReturnUrl=" + Request.Url.AbsoluteUri);
}
}
Hope that helps.
First of all, you should check authentication earlier in the pipeline.
Add this code in your Global.asax.cs:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (!this.Request.IsAuthenticated && !this.Request.Path.Contains("login.aspx"))
{
Response.Redirect("~/login.aspx?ReturnUrl=userLevel.aspx");
}
}
You check authentication for all pages/requests in 1 unique place.
So when you are in the Page_Load, you are sure to be logged in and authenticated.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["action"] == "getUserData")
{
string nm = User.Identity.Name;
Response.Clear();
Response.Write(nm);
Response.End();
}
}

web service is unable to return back to default page

I have asmx web service hosted on IIS and its purpose is to authenticate logined user.
when I run my code using visual studio and debug service is successfully called and authenticate user from DB but it is unable to transfer control back to my code that has default page.
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
Response.Redirect("Default.aspx");
Response.Cache.SetNoStore();
if (!Page.IsPostBack)
{
Session["Uri"] = Request.UrlReferrer;
}
this.hdnLoginStatus.InnerHtml = "";
if (!Page.IsPostBack)
{
new DAS().AuthenticateRequest();
if (HttpContext.Current.Items["LoginStatus"] == null)
return;
var key = (AuthWS.LoginStatus)HttpContext.Current.Items["LoginStatus"];
string msg = (string)GetGlobalResourceObject("Message", key.ToString()) ?? "";
this.ShowMessage(msg, MessageType.Warning);
this.hdnLoginStatus.InnerHtml = "SignedOutForcefully";
}
}
protected void LoginUser_LoggedIn(object sender, EventArgs e)
{
Response.Redirect("Default.aspx?key=" + (AuthWS.LoginStatus)HttpContext.Current.Items["LoginStatus"]);
}

Cookie does not work in 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);
}
}

asp.net - global.asax in asp.net 2.0 app

I created a global.asax file for an asp.net application. I run some code in the session_start method. The code does not get executed. Is there some type of procedure for using a global.asax file in asp.net 2.0?
I have the asax file itself and also a codebehind file.
Thank you!
Edit:
asax file:
<%# Application Codebehind="Global.asax.cs" Inherits="GrowUp.Global" %>
The code behind file:
using System;
using System.Collections;
using System.ComponentModel;
using System.Web;
using System.Web.SessionState;
namespace Ligdol
{
/// <summary>
/// Summary description for Global.
/// </summary>
public class Global : System.Web.HttpApplication
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
public Global()
{
InitializeComponent();
}
protected void Application_Start(Object sender, EventArgs e)
{
Application["HostName"] = System.Configuration.ConfigurationSettings.AppSettings["HostName"];
Application["counter"] = 1;
}
protected void Session_Start(Object sender, EventArgs e)
{
// Get the count from the application variable
int counter = int.Parse(Application["counter"].ToString());
//Check if a cookie exists.
if(HttpContext.Current.Request.Cookies["ligdolVersion"] != null)
{
//If a cookie exists, we need to redirect the user to the respective site.
if(HttpContext.Current.Request.Cookies["ligdolVersion"].ToString() == "new")
{
Response.StatusCode = 302;
Response.Status = "Moved temporarily";
Response.Redirect("http://beta.ligdol.co.il");
return;
}
else if(HttpContext.Current.Request.Cookies["ligdolVersion"].ToString() == "old")
{
return;
}
}
else if (counter == 40)
{
// If a cookie does not already exist,
//we need to check if the user is to be allowed to continue to the old site
//or be redirected to the new site.
//Note in a file that a user was redirected, so we can get an estimate of how many are being redirected.
System.IO.TextWriter tw = new System.IO.StreamWriter(#"redirect.log");
tw.WriteLine("Redirected to new site.");
tw.Close();
// Reset counter.
Application["counter"] = 1;
//write cookie made to expire in 30 days, by then the experiment will be over (we hope!).
HttpCookie cookie = new HttpCookie("ligdolVersion");
DateTime dtNow = DateTime.Now;
TimeSpan tsSpan = new TimeSpan(30, 0, 0, 0, 0);
cookie.Expires = dtNow + tsSpan;
cookie.Value = "new";
Response.Cookies.Add(cookie);
Response.Redirect("http://beta.ligdol.co.il");
return;
}
else
{
System.IO.TextWriter tw = new System.IO.StreamWriter(#"redirect.log");
tw.WriteLine("Redirected to old site.");
tw.Close();
HttpCookie cookie = new HttpCookie("ligdolVersion");
DateTime dtNow = DateTime.Now;
TimeSpan tsSpan = new TimeSpan(30, 0, 0, 0, 0);
cookie.Expires = dtNow + tsSpan;
cookie.Value = "old";
Response.Cookies.Add(cookie);
return;
}
}
protected void Application_BeginRequest(Object sender, EventArgs e)
{
}
protected void Application_EndRequest(Object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
}
protected void Application_Error(Object sender, EventArgs e)
{
}
protected void Session_End(Object sender, EventArgs e)
{
}
protected void Application_End(Object sender, EventArgs e)
{
}
#region Web Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
}
#endregion
}
}
The issue was the codebehind file. Once I put the code inline inside the asax file, it worked. This might be the only solution for old website projects.

Authentication in asp.net

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache );
Response.Cache.SetAllowResponseInBrowserHistory(false);
}
This code i have used to authenticate the website,its working but only when the user copies the url and paste it in a new window,but opening in the new window leads to the next page without any login credentials.
For authentication:
In page_Load Events
if (session(user_id) != null) {
response.redirect("the_page_which_you_want_to_go.aspx");
} else {
response.redirect("Login.aspx");
}

Resources