Answered by:
Cookies work in local project but not in server

Question
-
User206383436 posted
I am using cookies to save a GUID and distinguish among users that perform an operation. The method below is included in a class and it works fine when I test locally in my VS2017 project. However, it fails when the project is uploaded to a test server in which case I get a different GUID every time the operation is performed by the user which means that the cookie is not saved. The project is uploaded to a test site in a test server and the test site is ran from the same PC where my VS2017 project is located.
I will very much appreciate your feedback.
public String ObtenerCookies() { String strUserId = ""; if (HttpContext.Current.Request.Cookies["ccIdusuario"] != null) { HttpCookie UserIdCookie = HttpContext.Current.Request.Cookies["ccIdusuario"]; strUserId = UserIdCookie.Value.ToString(); } else { HttpCookie UserCookie = new HttpCookie("ccIdusuario"); strUserId = Guid.NewGuid().ToString(); UserCookie.Value = strUserId; UserCookie.Expires = DateTime.Now.AddYears(1); HttpContext.Current.Response.Cookies.Add(UserCookie); }
return strUserId; }Sunday, June 24, 2018 12:27 AM
Answers
-
User1724605321 posted
Hi JORGEMAL,
You can directly return the HttpResponseMessage :
public IHttpActionResult xxxx(xxx xxxxx) { var resp = new HttpResponseMessage(); ObtenerCookie(resp); return ResponseMessage(resp); }
public String ObtenerCookie(HttpResponseMessage resp) { String strUserId = ""; CookieHeaderValue cookie = Request.Headers.GetCookies("cosmohitsuserid").FirstOrDefault(); if (cookie != null) { strUserId = cookie["cosmohitsuserid"].Value; } else { strUserId = Guid.NewGuid().ToString(); cookie = new CookieHeaderValue("cosmohitsuserid", strUserId); cookie.Domain = Request.RequestUri.Host; cookie.Expires = DateTime.Now.AddYears(1); cookie.Path = "/"; resp.Headers.AddCookies(new CookieHeaderValue[] { cookie }); } return strUserId; }
Best Regards,Nan Yu
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, June 27, 2018 3:22 AM
All replies
-
User1724605321 posted
Hi JORGEMAL,
I can't reproduce your problem . But you can refer to below thread for checking the potential causes such as server time is not correct :
https://stackoverflow.com/a/47905039
Hope it helps.
Best Regards,
Nan Yu
Monday, June 25, 2018 7:22 AM -
User206383436 posted
Thanks for your reply.
I had already seen that thread. The server time zone and time are correctly set. Such a thread refers to several things that might prevent cookies from working correctly and the only one that seems to apply here is the one about the web.config file but I have not found how to verify it.I am using this exact same method (ObtenerCookies()) in a web form project located in the same server without trouble. It is another website hosted in the same server.
The difference I see is that now I am using it in an MVC project that consumes a Web API, a RESTful service. I wonder if this has something to do. (This is, in fact, my first ASP.NET MVC project).For testing puposes, this is what I am currently doing. The Web API is called from AJAX.
public class waInteractivasController : ApiController { [HttpPost] [Route("api/VotoInteractiva/{parameters}")] public IHttpActionResult RegistraVoto(String parameters) { SeccEspVotacionVotosMVC objSeccEspVotacionVotosMVC = new SeccEspVotacionVotosMVC(); objSeccEspVotacionVotosMVC.ObtenerCookies(); return Ok(""); } }
I know that the cookie is not being saved because I am writing to a text file the result of executing the method ObtenerCookies(). The below content is saved to the text file if the Request.Cookies is null which means that the cookie does not exist.
2018/06/25 16:48:33 AD ------------------------------------------------------------------------------ 2018/06/25 16:48:33 AD 1. Cookie does not exist. 2018/06/25 16:48:33 AD 2. New cookie is created. 2018/06/25 16:48:33 AD 3. Properties are assigned to the cookie. 2018/06/25 16:48:33 AD 4. Cookie value fe9956a9-2a7e-4929-8568-11321f37d07c 2018/06/25 16:49:07 AD ------------------------------------------------------------------------------ 2018/06/25 16:49:07 AD 1. Cookie does not exist. 2018/06/25 16:49:07 AD 2. New cookie is created. 2018/06/25 16:49:07 AD 3. Properties are assigned to the cookie. 2018/06/25 16:49:07 AD 4. Cookie value bc8f5fe8-824d-42ae-86ad-1595c81068d4
I will appreciate if you have additional feedback.
Monday, June 25, 2018 10:16 PM -
User1724605321 posted
Hi JORGEMAL,
Everything the API endpoint needs must be sent along with the request either in the URL, the request headers or the request body :
var resp = new HttpResponseMessage(); ... //create and set cookie in response var cookie = new CookieHeaderValue("customCookie", "cookieVal"); cookie.Expires = DateTimeOffset.Now.AddDays(1); cookie.Domain = Request.RequestUri.Host; cookie.Path = "/"; resp.Headers.AddCookies(new CookieHeaderValue[] { cookie }); return resp;
Please refer to link below for explanation and code sample :
https://www.c-sharpcorner.com/UploadFile/2b481f/how-to-set-cookies-in-Asp-Net-web-api/
Best Regards,
Nan Yu
Tuesday, June 26, 2018 3:11 AM -
User206383436 posted
Well, I have reviewed the content in the 2 links you provided and also found this additional source:
https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/http-cookies
I implemented my code but still the cookie is not saved. Obviously, I am doing something wrong and I kindly ask for your feedback on my code. The lines of code "Utilerias.NuevoEventoSistema" generate an entry to a text (log) file and I always get "The cookie does not exist". Below you will find the 2 controllers that compose the Web API.
[HttpPost] [Route("api/VotoInteractiva/{parameters}")] public IHttpActionResult RegistraVoto(String parameters) { ObtenerCookie(); return Ok(""); } public String ObtenerCookie() { var resp = new HttpResponseMessage(); String strUserId = ""; CookieHeaderValue cookie = Request.Headers.GetCookies("cosmohitsuserid").FirstOrDefault(); Utilerias.NuevoEventoSistema("-----------------------------------", "", "", "", ""); if (cookie != null) { strUserId = cookie["cosmohitsuserid"].Value; Utilerias.NuevoEventoSistema("The cookie exists", strUserId, "", "", ""); } else { strUserId = Guid.NewGuid().ToString(); cookie = new CookieHeaderValue("cosmohitsuserid", strUserId); cookie.Expires = DateTime.Now.AddYears(1); resp.Headers.AddCookies(new CookieHeaderValue[] { cookie }); Utilerias.NuevoEventoSistema("The cookie does not exist", strUserId, "", "", ""); } return strUserId; }
Tuesday, June 26, 2018 9:52 PM -
User1724605321 posted
Hi JORGEMAL,
You can directly return the HttpResponseMessage :
public IHttpActionResult xxxx(xxx xxxxx) { var resp = new HttpResponseMessage(); ObtenerCookie(resp); return ResponseMessage(resp); }
public String ObtenerCookie(HttpResponseMessage resp) { String strUserId = ""; CookieHeaderValue cookie = Request.Headers.GetCookies("cosmohitsuserid").FirstOrDefault(); if (cookie != null) { strUserId = cookie["cosmohitsuserid"].Value; } else { strUserId = Guid.NewGuid().ToString(); cookie = new CookieHeaderValue("cosmohitsuserid", strUserId); cookie.Domain = Request.RequestUri.Host; cookie.Expires = DateTime.Now.AddYears(1); cookie.Path = "/"; resp.Headers.AddCookies(new CookieHeaderValue[] { cookie }); } return strUserId; }
Best Regards,Nan Yu
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, June 27, 2018 3:22 AM -
User206383436 posted
Finally working !!!
The trick is to return the HttpResponseMessage from the controller that performs the main web service. Well, my main issue is solved and now I just have to arrange the code to my specific needs.Thanks a lot for your support and patience. I really appreciate it very, very much.
Respectfully,
Jorge MaldonadoWednesday, June 27, 2018 5:16 PM -
User206383436 posted
I uploaded the project to the server and cookies failed. However, it works in my local PC when I run it in VS2017. I keep getting "The cookie does not exist" in my log file.
Is there a special consideration I must take into account in order to run it in the server?
[HttpPost] [Route("api/VotoInteractiva/{parameters}")] public IHttpActionResult RegistraVoto(String parameters) { var resp = new HttpResponseMessage(); String strUserId = ObtenerCookie(resp); return ResponseMessage(resp); } public String ObtenerCookie(HttpResponseMessage resp) { String strUserId = ""; CookieHeaderValue cookie = Request.Headers.GetCookies("cosmohitsuserid").FirstOrDefault(); Utilerias.NuevoEventoSistema("-----------------------------------", "", "", "", ""); if (cookie != null) { strUserId = cookie["cosmohitsuserid"].Value; Utilerias.NuevoEventoSistema("The cookie exists", strUserId, "", "", ""); } else { strUserId = Guid.NewGuid().ToString(); cookie = new CookieHeaderValue("cosmohitsuserid", strUserId); cookie.Expires = DateTime.Now.AddYears(1); cookie.Domain = Request.RequestUri.Host; cookie.Path = "/"; resp.Headers.AddCookies(new CookieHeaderValue[] { cookie }); Utilerias.NuevoEventoSistema("The cookie does not exist", strUserId, "", "", ""); } return strUserId; }
Thursday, June 28, 2018 6:56 PM