I have a javascript function that updates a cookie in the following manner:
aspx page:
function setCookie()
{
//...
document.cookie = "myCookie = HelloWorld";
//...
}
After an asp control triggers an event, the entire page gets sent back from the client. I want to be able to read the value of my cookie. How do I do that?
I've tried:
string temp = Request.ServerVariables["myCookie"].ToString(); but that is the wrong way to do it.
How do I read the client cookie on the server
if(Request.Cookies["userName"] != null)
Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);
Source MSDN
Here is the helper method to retrieve cookie at server side.
public static String GetCookie(String cookieName)
{
try
{
if (HttpContext.Current.Request.Cookies[cookieName] == null)
return String.Empty;
return HttpContext.Current.Request.Cookies[cookieName].Value;
}
catch
{
return String.Empty;
}
}
Usage
var result = GetCookie("myCookie");
If you want to set cookie at client side, look at this Cookie plugin.
Related
using asp.net/c#, how is possible to :
display a webform only when the cookie value has been set to "1". (on page_load event)
So the asp code should just read the cookie value and make visible/invisible the webform
Note that the cookie value I will set it with php.
Note that the html webform is included in the code:
asp:Content ID="webform" ContentPlaceHolderID="webform1" runat="Server"
So I need a way to manipulate this webform depending of the settings of the cookie value that I will read all the time the page gets loaded
if (!Page.IsPostback)
Call the method below, based on the return value response.redirect to another page.
private string GetCookieValue(string cookieName, string itemName)
{
var CookieName = "MY_COOKIE";
var CookieValue = string.empty;
HttpCookie myCookie = Request.Cookies[CookieName];
if (myCookie == null) return "No cookie found";
//If you added a key vs. the value in the cookie use this code
//CookieValue = myCookie[itemName].ToString();
//Get the value of the cookie if you are not using a key
CookieValue = myCookie.Value.ToString();
Return CookieValue;
}
I have web application in Asp.Net MVC4 and I want to use cookie for user's login and logout. So my actions as follows:
Login Action
[HttpPost]
public ActionResult Login(string username, string pass)
{
if (ModelState.IsValid)
{
var newUser = _userRepository.GetUserByNameAndPassword(username, pass);
if (newUser != null)
{
var json = JsonConvert.SerializeObject(newUser);
var userCookie = new HttpCookie("user", json);
userCookie.Expires.AddDays(365);
HttpContext.Response.Cookies.Add(userCookie);
return RedirectToActionPermanent("Index");
}
}
return View("UserLog");
}
LogOut Action
public ActionResult UserOut()
{
if (Request.Cookies["user"] != null)
{
var user = new HttpCookie("user")
{
Expires = DateTime.Now.AddDays(-1),
Value = null
};
Response.Cookies.Add(user);
}
return RedirectToActionPermanent("UserLog");
}
And I use this cookie in _Loyout as follow:
#using EShop.Core
#using Newtonsoft.Json
#{
var userInCookie = Request.Cookies["user"];
}
...
#if (userInCookie != null && userInCookie.Value)
{
<li>Salam</li>
<li>Cıxış</li>
}
else
{
<li>Giriş</li>
}
But When I click *UserOut* action this action happen first time, but then it doesn't work. I put breakpoint for looking process but it get UserLog action doesn't UserOut.
My question is that where I use wrong way of cookie? What is a best way using cookie in Asp.Net Mvc4 for this scenario ?
Try using Response.SetCookie(), because Response.Cookies.Add() can cause multiple cookies to be added, whereas SetCookie will update an existing cookie.
We are using Response.SetCookie() for update the old one cookies and Response.Cookies.Add() are use to add the new cookies. Here below code CompanyId is update in old cookie[OldCookieName].
HttpCookie cookie = Request.Cookies["OldCookieName"];//Get the existing cookie by cookie name.
cookie.Values["CompanyID"] = Convert.ToString(CompanyId);
Response.SetCookie(cookie); //SetCookie() is used for update the cookie.
Response.Cookies.Add(cookie); //The Cookie.Add() used for Add the cookie.
userCookie.Expires.AddDays(365);
This line of code doesn't do anything. It is the equivalent of:
DateTime temp = userCookie.Expires.AddDays(365);
//do nothing with temp
You probably want
userCookie.Expires = DateTime.Now.AddDays(365);
I don't really understand the difference between request cookie and response cookie. And it seem like everytime I postback, if I don't manually rewrite the cookie from request to response, then it disappears. How do I solve this?
public string getCookie(string name) {
if (Request.Cookies["MyApp"] != null && Request.Cookies["MyApp"][name] != null) {
return Request.Cookies["MyApp"][name];
} else if (Response.Cookies["MyApp"] != null && Response.Cookies["MyApp"][name] != null) {
return Response.Cookies["MyApp"][name];
} else {
return "";
}
}
public void writeCookie(string name, string value) {
Response.Cookies["MyApp"][name] = value;
HttpCookie newCookie = new HttpCookie(name, value);
newCookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(newCookie);
}
Request.Cookies["MyApp"];
Code above will return you a cookie with name "MyApp" Doing this:
Request.Cookies["MyApp"][name]
You are taking value "name" from cookie called "MyApp".
But in your setCookie code you are setting a cookie with called name and do not create a cookie called "MyApp":
HttpCookie newCookie = new HttpCookie(name, value);
newCookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(newCookie);
So, you should remove ["MyApp"] from any place you have it, or you may do something like this in setCookie:
public void writeCookie(string name, string value) {
if(Response.Cookies["MyApp"] == null) {
HttpCookie newCookie = new HttpCookie("MyApp");
newCookie.Expires = DateTime.Now.AddYears(1);
Response.SetCookie(newCookie);
}
if(Response.Cookies["MyApp"][name] == null)
Response.Cookies["MyApp"].Values.Add(name, value);
else
Response.Cookies["MyApp"][name] = val;
// or maybe simple Response.Cookies["MyApp"][name] = val; will work fine, not sure here
}
Request is the "thing" you get when the user tries to get to your website, while Response is a way of responding to this request.
In other words, see the official msdn documentation, namely this part:
ASP.NET includes two intrinsic cookie collections. The collection
accessed through the Cookies collection of HttpRequest contains
cookies transmitted by the client to the server in the Cookie header.
The collection accessed through the Cookies collection of HttpResponse
contains new cookies created on the server and transmitted to the
client in the Set-Cookie header.
http://msdn.microsoft.com/en-us/library/system.web.httprequest.cookies.aspx
So no, you don't have to create new cookies every time, unless they have already expired. Just be sure you reference the right collection of cookies.
You might want to check the domain and path that are being assigned to the cookie. It could be that your saved cookies are just being orphaned because the path is too specific or because the wrong domain is being set.
Domain is the server name that the browser sees such as "yourdomain.com". If the cookie is set with a different domain than this then the browser will never send it back. Likewise, the path of the cookie is the path to the resource being requested such as "/forum/admin/index" etc. The cookie is sent for that location and all child locations, but not for parent locations. A cookie set for "/forum/admin/index" will not be sent if you're accessing a page that sits in the "/forum" directory.
I don't typically play with Cookies, but I wanted to look into this one verses the Session variables I typically use.
If I set a Cookie, then immediately try to read from it, I do not get the value back that I just set it to.
However, if I refresh the page or close the browser and open it back up, the Cookie appears to be set.
I'm debugging this in Chrome. Would that make any difference?
public const string COOKIE = "CompanyCookie1";
private const int TIMEOUT = 10;
private string Cookie1 {
get {
HttpCookie cookie = Request.Cookies[COOKIE];
if (cookie != null) {
TimeSpan span = (cookie.Expires - DateTime.Now);
if (span.Minutes < TIMEOUT) {
string value = cookie.Value;
if (!String.IsNullOrEmpty(value)) {
string[] split = value.Split('=');
return split[split.Length - 1];
}
return cookie.Value;
}
}
return null;
}
set {
HttpCookie cookie = new HttpCookie(COOKIE);
cookie[COOKIE] = value;
int minutes = String.IsNullOrEmpty(value) ? -1 : TIMEOUT;
cookie.Expires = DateTime.Now.AddMinutes(minutes);
Response.Cookies.Add(cookie);
}
}
Below is how I use it:
public Employee ActiveEmployee {
get {
string num = Request.QueryString["num"];
string empNum = String.IsNullOrEmpty(num) ? Cookie1 : num;
return GetActiveEmployee(empNum);
}
set {
Cookie1 = (value != null) ? value.Badge : null;
}
}
This is how I am calling it, where Request.QueryString["num"] returns NULL so that Cookie1 is being read from:
ActiveEmployee = new Employee() { Badge = "000000" };
Console.WriteLine(ActiveEmployee.Badge); // ActiveEmployee is NULL
...but reading from Cookie1 is returning null also.
Is there a command like Commit() that I need to call so that a cookie value is immediately available?
Cookies are not like Session- there are two cookie collections, not one.
Request.Cookies != Response.Cookies. The former is the set of cookies that are sent from the browser when they request the page, the latter is what you send back with the content. This is exposing the nature of the cookies RFC, unlike Session, which is a purely Microsoft construct.
When you set a cookie in a response it does not get magically transported into the request cookies collection. It's there in the response, you're free to check for it there, but it won't appear in the request object until it actually is sent from the browser in the next request.
To add to the other answers, you can get around the problem by caching the value in a private variable in case the cookie hasn't been updated yet:
private string _cookie1Value = null;
private string Cookie1 {
get {
if (_cookie1Value == null)
{
// insert current code
_cookie1Value = cookie.Value;
}
return _cookie1Value;
}
set {
// insert current code
_cookie1Value = value;
}
}
To simply put it; A cookie that is set in response, will only be available for the next htpp request (a next get or post action from the browser).
In detail: When a cookie value is set in HttpResponse, it will be persisted/stored only when after the response reaches client (meaning the browser will read the cookie value from Http Response header and save it). So, technically only for the henceforth requests it will be available. Example, when the user clicks on a link or a button that makes server call after this cycle from the browser.
Hope this gives you some idea, I suggest you read the What are cookies and ASP.NET wraps it before using it.
I have a file upload in my site which is done using uploadify it uses a ashx page to upload file to database.It works fine in IE but in Mozilla the context.Session is getting null.I have also used IReadOnlySessionState to read session.
how can i get session in Mozilla like IE.
here is the ashx code i have done
public class Upload : IHttpHandler, IReadOnlySessionState
{
HttpContext context;
public void ProcessRequest(HttpContext context)
{
string UserID = context.Request["UserID"];
context.Response.ContentType = "text/plain";
context.Response.Expires = -1;
XmlDocument xDoc = new XmlDocument();
HttpPostedFile postedFile = context.Request.Files["Filedata"];
try
{
if (context.Session["User"] == null || context.Session["User"].ToString() == "")
{
context.Response.Write("SessionExpired");
context.Response.StatusCode = 200;
}
else
{
// does the uploading to database
}
}
}
}
In IE Context.Session["User"] always have the value but in Mozilla it is always null
You need to add sessionId to uploadify post params and restore ASP.NET_SessionId cookie on the server side on global.asax at OnBeginRequest. It is actually bug with flash and cookies.
I have created module for session and auth cookie restore, to get work flash and asp.net session, so i think it will be useful for your:
public class SwfUploadSupportModule : IHttpModule
{
public void Dispose()
{
// clean-up code here.
}
public void Init(HttpApplication application)
{
application.BeginRequest += new EventHandler(OnBeginRequest);
}
private void OnBeginRequest(object sender, EventArgs e)
{
var httpApplication = (HttpApplication)sender;
/* we guess at this point session is not already retrieved by application so we recreate cookie with the session id... */
try
{
string session_param_name = "ASPSESSID";
string session_cookie_name = "ASP.NET_SessionId";
if (httpApplication.Request.Form[session_param_name] != null)
{
UpdateCookie(httpApplication, session_cookie_name, httpApplication.Request.Form[session_param_name]);
}
else if (httpApplication.Request.QueryString[session_param_name] != null)
{
UpdateCookie(httpApplication, session_cookie_name, httpApplication.Request.QueryString[session_param_name]);
}
}
catch
{
}
try
{
string auth_param_name = "AUTHID";
string auth_cookie_name = FormsAuthentication.FormsCookieName;
if (httpApplication.Request.Form[auth_param_name] != null)
{
UpdateCookie(httpApplication, auth_cookie_name, httpApplication.Request.Form[auth_param_name]);
}
else if (httpApplication.Request.QueryString[auth_param_name] != null)
{
UpdateCookie(httpApplication, auth_cookie_name, httpApplication.Request.QueryString[auth_param_name]);
}
}
catch
{
}
}
private void UpdateCookie(HttpApplication application, string cookie_name, string cookie_value)
{
var httpApplication = (HttpApplication)application;
HttpCookie cookie = httpApplication.Request.Cookies.Get(cookie_name);
if (null == cookie)
{
cookie = new HttpCookie(cookie_name);
}
cookie.Value = cookie_value;
httpApplication.Request.Cookies.Set(cookie);
}
}
Also than you need register above module at web.config:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="SwfUploadSupportModule" type="namespace.SwfUploadSupportModule, application name" />
</modules>
</system.webServer>
Context.Session is null.. because connection to HttpHandler has another Context.Session
(debug and try: Context.Session.SessionId in where is the fileInput is different from Context.Session.SessionId in Upload.ashx)!
I suggest a workaround: pass a reference to the elements you need in the second session ( in my sample i pass the original SessionId using sessionId variable)
....
var sessionId = "<%=Context.Session.SessionID%>";
var theString = "other param,if needed";
$(document).ready(function () {
$('#fileInput').uploadify({
'uploader': '<%=ResolveUrl("~/uploadify/uploadify.swf")%>',
'script': '<%=ResolveUrl("~/Upload.ashx")%>',
'scriptData': { 'sessionId': sessionId, 'foo': theString },
'cancelImg': '<%=ResolveUrl("~/uploadify/cancel.png")%>',
....
and use this items in .ashx file.
public void ProcessRequest(HttpContext context)
{
try
{
HttpPostedFile file = context.Request.Files["Filedata"];
string sessionId = context.Request["sessionId"].ToString();
....
If you need to share complex elements use Context.Application instead of Context.Session, using original SessionID: Context.Application["SharedElement"+SessionID]
It's likely to be something failing to be set by the server or sent back on the client.
Step back to a lower level - use a network diagnostic tool such as Fiddler or Wireshark to examine the traffic being sent to/from your server and compare the differences between IE and Firefox.
Look at the headers to ensure that cookies and form values are being sent back to the server as expected.
I have created a function to check session have expired and then pass that as a parameter in script-data of uploadify and in ashx file i check that parameter to see whether session exists or not.if it returns session have expired then upload will not take place.It worked for me. Did not find any issues using that. hope that solve my issue
I had a similar problem with an .ashx file. The solution was that the handler has to implement IReadOnlySessionState (for read-only access) or IRequiresSessionState (for read-write access). eg:
public class SwfUploadSupportModule : IHttpHandler, IRequiresSessionState { ... }
These Interfaces do not need any additional code but act as markers for the framework.
Hope that this helps.
Jonathan