huy tran tan
huy tran tan

Reputation: 23

Can not read all cookies of a request in asp.net core

I'm coding in asp.net core mvc. My problem is a set somes cookie by javascript, but in the asp.net core mvc controller, I cannot retrieve value of a specific key I had set before. And then I try counting number of key are existing in the cookie list.

string strCart = Request.Cookies.Count().ToString();

The output is 2 despite It must be 3 and the key I want to get is missing in Request.Cookies

Edit: This is the js code

function SetCookie(cname, cvalue, exdays,cpath) 
{ 
  let d = new Date(); 
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  let expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/" + cpath;
} 

it works on directly with php but got the problem with asp.net core

Upvotes: 1

Views: 3319

Answers (2)

huy tran tan
huy tran tan

Reputation: 23

Thanks for supporting me, now I've found the problem of my code. The problem is when setting cookie value I forgot to escape the string's character. In php or js, it is accepted, but c# is strong type language and c# uses double quote to determine a string so the json string has character that cause the conflict. After that, the result is the specific cookie is missing

Upvotes: 0

Christopher
Christopher

Reputation: 9804

In ASP.Net, you do not do a lot of level stuff. Stuff like creating a cookie is right on the level you do not usually do. ASP.Net has a lot of Automagics to make programming here easier. A automagic for storing and retreiving a Session ID via cookies and Link values is among them. That code might easily swallow a cookie that was creatred client side, without the server knowing of it. It could even be a active security measure - allowing any random value to be set by the Client Request has prooven troublesome time and time again.

Based on one comment, this is what you expect: cart=[{"id":1,"qty":6}]. So I am going to guess for a Online Shop. Now data like a cart really does not belong onto the client side. It is too easy for a attacker to break your code by throwing unexpected values at you. Never trust user Input. And with any networking, that distrust should be cubed.

I think when they allow you to use the cart before you logged in, what they do is give you a Session ID regardless of login state. Usually you only get SID's after a login. But Onlineshops tend to give ones to everyone that does not send one along with the Request. It is SID's for everyone. If they later do log in or create a account, it is just a mater of linking the session to the account, copying the cart on the server side or something similar like that.

Upvotes: 1

Related Questions