Setting a Cookie in C# - c#

I am trying to set a rememberMe cookie. It works however the domain it is being set to is using the subdomain as well as the main domain .... How can I set it to use just the main domain? I have tried rememberMeCookie.Domain = "MyNewDomain"; but then no cookie gets set.
I need the cookie to be set to the main domain in order for my rememberMe cookie to be read from another site as I am implementing a SSO procedure.
var rememberUrlSelection = Request.Cookies["rememberUrlSelection_" + Session["GuiId"]];
if (login.RememberMe || !login.RememberMe)
{
if (Request.Cookies["rememberMeWf"] == null)
{
HttpCookie rememberMeCookie = new HttpCookie("rememberMeWf");
var val = Newtonsoft.Json.JsonConvert.DeserializeObject<ApiResponse>(apiResp.Content);
string remC = Newtonsoft.Json.JsonConvert.SerializeObject(val.responseObject);
rememberMeCookie.Value = remC.UrlEncode();
rememberMeCookie.Expires = DateTime.Now.AddMonths(3);
rememberMeCookie.Domain = "MyNewDomain";
Response.Cookies.Add(rememberMeCookie);
}
}

You can try:-
cookie.Domain = Request.RequestUri.Host;
var rememberUrlSelection =
Request.Cookies["rememberUrlSelection_" + Session["GuiId"]];
if (login.RememberMe || !login.RememberMe) {
if (Request.Cookies["rememberMeWf"] == null) {
HttpCookie rememberMeCookie = new HttpCookie("rememberMeWf");
var val = Newtonsoft.Json.JsonConvert.DeserializeObject<ApiResponse>(
apiResp.Content);
string remC =
Newtonsoft.Json.JsonConvert.SerializeObject(val.responseObject);
rememberMeCookie.Value = remC.UrlEncode();
rememberMeCookie.Expires = DateTime.Now.AddMonths(3);
// rememberMeCookie.Domain = "MyNewDomain";
rememberMeCookie.Domain = Request.RequestUri.Host;
Response.Cookies.Add(rememberMeCookie);
}
}

Related

How To generate cookie in C# and read with JS in MVC through HTTPS

I'm generating a cookie in C#, and attempting to read it in JQuery in an ascx on page load. The site is a mad mixture of MVC and ANgularJS, but in this instance I'm purely looking in the ascx. The site runs in https.
C# cookie generation:
private void UpdateSessionTimerCookie(bool? loggedIn = true)
{
#region Not Logged in? Return nothing
var isLoggedIn = loggedIn ?? false;
if (!isLoggedIn) { return; }
#endregion
const string cookieName = "sRoller";
#region Delete the cookie if it already exists
if (Request.Cookies.Exists(cookieName) && Request.Cookies[cookieName] != null)
{
Response.Cookies.Remove(cookieName);
Request.Cookies.Remove(cookieName);
}
#endregion
#region Build the new cookie (reset of timer)
var cookie = new HttpCookie(cookieName)
{
HttpOnly = false,
SameSite = SameSiteMode.Lax,
Expires = DateTime.Now.AddMinutes(HttpContext.Session.Timeout),
Value = DateTime.Now.ToString(),
Path = "/",
Secure = true,
Shareable = false
};
Response.Cookies.Add(cookie);
Response.SetCookie(cookie);
#endregion
}
Attempted cookie read in ascx:
<script type="text/javascript">
$(document).ready(function() {
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1);
if (c.indexOf(name) === 0) return c.substring(name.length, c.length);
}
return "";
}
var myCookie = getCookie("sRoller");
//first alert
alert(myCookie);
});
function ShowCookie() {
var MyCookie = getCookieValue("sRoller");
//second alert
alert(MyCookie);
}
function getCookieValue(name) {
var cookieList = document.cookie.split('; ');
var cookies = {};
for (var i = cookieList.length - 1; i >= 0; i--) {
var cookie = cookieList[i].split('=');
cookies[cookie[0]] = cookie[1];
}
return cookies[name];
}
ShowCookie();
</script>
In the first alert, I get "undefined". In the second alert, I get nothing.
I've checked dev tools, and the cookie is there.
Try this:
function getCookieValue(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
This solution is better, because you do not have to iterate over all cookies. I tested this in a private window in my browser.
More ways of getting cookies by value:
Get cookie by name

Asp.Net MVC Changing Resource Values Without Clearing Cache Manually

In my Asp.Net MVC application users are coming from another system and I'm logging them in like below.
IAccount account = null;
if (userType == UserType.SystemUser)
account = _accountService.CheckSystemUser(userId);
if (userType == UserType.Employee)
account = _accountService.CheckEmployee(userId);
if (account == null) throw new Exception(ErrorMessages.UserNotFound);
var roles = account.Roles.ToArray();
var principalModel = new CustomPrincipalViewModel
{
UserId = account.UserId.ToString(),
FullName = account.FullName,
Roles = roles,
Language = account.Language
};
var userData = JsonConvert.SerializeObject(principalModel);
var ticket = new FormsAuthenticationTicket(1, principalModel.FullName, DateTime.Now, DateTime.Now.AddMinutes(30), false, userData);
var encryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(cookie);
SetCulture(account.Language.CultureCode);
return Json(new { isSuccess = true, userFullName = account.FullName });
And setting current culture like this with SetCulture method.
private void SetCulture(string culture)
{
culture = CultureHelper.GetImplementedCulture(culture);
var cookie = Request.Cookies["_culture"];
if (cookie != null)
{
cookie.Value = culture;
cookie.Expires = DateTime.Now.AddYears(1);
}
else
{
cookie = new HttpCookie("_culture")
{
Value = culture,
Expires = DateTime.Now.AddYears(1)
};
}
Response.Cookies.Add(cookie);
}
And my view pages I'm setting text values from Resource files like below.
<span class="pageButton"> #Global.Cancel </span>
But when I change user language from other system and log in again to my system, all texts are still in previous language. After I refresh my page with ctrl+F5 everything looks in true language.
Is there a way to force to load page texts in new language without clearing cache manually ?
The problem in cookie var cookie = Request.Cookies["_culture"];, still keep old value, clean it when you logOff or when you try to log-In again
And you can use also Thread.CurrentThread to set culture
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

ASPX Cookies lost

I have an issue with ASP.NET cookies being lost between requests.
I have an ASCX control which has multiple filtering checkboxes. I can check/uncheck these checkboxes and then I click a . In this applyFilters method, I am setting cookies based on whether the checkboxes are checked/unchecked. The code that does this is :
public void setFilterCookie(string name, string val)
{
if (!String.IsNullOrEmpty(val) && (val != null && !val.Equals("-1")))
{
if (request.Cookies[name] != null)
{
HttpCookie myCookie = new HttpCookie(name);
myCookie.Expires = DateTime.Now.AddDays(-2d);
response.Cookies.Add(myCookie);
request.Cookies.Remove(name);
}
HttpCookie cookie = new HttpCookie(name, val);
cookie.Expires = DateTime.Now.AddDays(5);
response.Cookies.Add(cookie);
}
else
{
if (request.Cookies[name] != null)
{
HttpCookie myCookie = new HttpCookie(name);
myCookie.Expires = DateTime.Now.AddDays(-2d);
response.Cookies.Add(myCookie);
request.Cookies.Remove(name);
}
}
}
After the cookies are set, I want to databind a grid from the parent container of the control. In this databind method I am reading the cookies using the following method :
public string getCookie(string cookieName)
{
if (isNotNullOrEmpty(cookieName))
return request.Cookies[cookieName].Value.ToString().Trim();
else
return null;
}
The problem is that when I am setting the cookies, I can see the values being set (e.g. response.Cookies["Domain"] = "5") but when I am reading them the value is string empty.
Can somebody tell me what is wrong?
Thank you
You shouldn't be removing request cookies and adding response cookies with the same name multiple times. This should work.
public void setFilterCookie(string name, string val)
{
var cookieValue = string.Empty;
var expires = 0;
if (!string.IsNullOrWhiteSpace(val) && !val.Equals("-1"))
{
cookieValue = val;
expires = 5;
}
else
{
expires = -2;
}
var cookie = new HttpCookie(name, cookieValue) {Expires = DateTime.Now.AddDays(expires)};
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}

How to remove cookie from server side in c#

I have an asp.net mvc 4 project where try to update my cookie, but instead of this it's create another cookie, and for example I have a 3 duplicate cookies with name "page". Anybody know how to fix this?
if (page != null && Request.Browser.Cookies) {
if (Response.Cookies.AllKeys.Contains("page")) {
var aCookie = new HttpCookie("page") { Expires = DateTime.Now.AddDays(-1) };
Response.Cookies.Add(aCookie);
}
var pages = new HttpCookie("page") { Value = page.ToString(), Expires = DateTime.Now.AddDays(7) };
Response.Cookies.Add(pages);
}
If you want to remove your cookie from client, you should set it as expired:
if (page != null && Request.Browser.Cookies) {
Response.Cookies.Remove("page");
var aCookie = new HttpCookie("page") { Expires = DateTime.Now.AddDays(-1) };
Response.Cookies.Add(aCookie);
}
But if you only need to update it, just remove it from response and add a new version of it:
if (page != null && Request.Browser.Cookies) {
Response.Cookies.Remove("page");
var pages = new HttpCookie("page") { Value = page.ToString(), Expires = DateTime.Now.AddDays(7) };
Response.Cookies.Add(pages);
}
Have you tried removing the cookie before adding the new one.
if (page != null && Request.Browser.Cookies)
{
Response.Cookies.Remove("page");
var pages = new HttpCookie("page") { Value = page.ToString(), Expires = DateTime.Now.AddDays(7) };
Response.Cookies.Add(pages);
}
Note that Response.Cookies.Remove("page") will not throw an exception if the is no page cookie, so testing for its existence is not required.

store user latest visit pages in cookie

I want to store user latest visited pages in a cookie. It has 2 parts, PageTitle and URL.
I use the code below but it just save a value in first page load and don't change it in other page loads.
if (Request.Cookies["latestvisit"] == null)
{
HttpCookie myCookie = new HttpCookie("latestvisit");
myCookie.Expires = DateTime.Now.AddYears(1);
myCookie.Values[title] = System.Web.HttpUtility.UrlEncode(URL);
Response.Cookies.Add(myCookie);
}
else
{
System.Collections.Specialized.NameValueCollection cookieCollection = Request.Cookies["latestvisit"].Values;
string[] CookieTitles = cookieCollection.AllKeys;
//mj-y: If the url is reapeated, move it to end(means make it newer by removing it and adding it again)
string cookieURL = "";
foreach (string cookTit in CookieTitles)
{
cookieURL = System.Web.HttpUtility.UrlDecode(Request.Cookies["latestvisit"].Values[cookTit]);
if (cookieURL == URL)
{
cookieCollection.Remove(cookTit);
cookieCollection.Set(title, URL);
return;
}
}
//mj-y: If it was not repeated ...
if (cookieCollection.Count >15) // store just 15 item
cookieCollection.Remove(CookieTitles[0]);
cookieCollection.Set(title, URL);
}
and of course I want to code the url and decode it, so user cant determine the content of the cookie, how can I do it?
Try this:
if (Request.Cookies["latestVisit"] == null)
{
HttpCookie myCookie = new HttpCookie("latestVisit");
myCookie.Expires = DateTime.Now.AddYears(1);
myCookie.Values[title] = System.Web.HttpUtility.UrlEncode(URL);
Response.Cookies.Add(myCookie);
}
else
{
var myCookie = Request.Cookies["latestVisit"];
var cookieCollection = myCookie.Values;
string[] CookieTitles = cookieCollection.AllKeys;
//mj-y: If the url is reapeated, move it to end(means make it newer by removing it and adding it again)
string cookieURL = "";
foreach (string cookTit in CookieTitles)
{
cookieURL = System.Web.HttpUtility.UrlDecode(Request.Cookies["latestVisit"].Values[cookTit]);
if (cookieURL == URL)
{
cookieCollection.Remove(cookTit);
cookieCollection.Set(title, System.Web.HttpUtility.UrlEncode(URL));
Response.SetCookie(myCookie);
return;
}
}
//mj-y: If it was not repeated ...
cookieCollection.Set(title, System.Web.HttpUtility.UrlEncode(URL));
if (cookieCollection.Count > 15) // store just 15 item
cookieCollection.Remove(CookieTitles[0]);
Response.SetCookie(myCookie);
}
As a safe practice, I'd also recommend you to encode the title variable before adding it to the values collection, for example:
myCookie.Values[System.Web.HttpUtility.UrlEncode(title)]
= System.Web.HttpUtility.UrlEncode(URL);
and
cookieCollection.Set(System.Web.HttpUtility.UrlEncode(title),
System.Web.HttpUtility.UrlEncode(URL));

Categories

Resources