0

What this cookie aims is (if the cookie exists) to remember CartId so that user anonymous or registered can see his cart. If cookie doesn't exists it creates one with GuId and stores the cartId for some period of time.

I tried in some way to achieve that in this code: enter image description here

And here cookie isn't working. It saves only cookie in line 190 with CartId always 0 and the other if and else statements are not checked. The line 190 I wrote it because it was throwing null exception statement without this line.Also I think that a mistake that I made is that I didn't use Current context above of line 197. I tried to use HttpContext.Current and it throws this error : enter image description here

Help me out please if it can be fixed. Any other example or url of cookies c# shopping cart is accepted. Thank you in advance.

First attempt:

public string GetCartId(HttpContextBase context )
    {

       if (context.Request.Cookies["CartId"] == null) return "0";

        string cartId = context.Request.Cookies["CartId"].Value;
        {
            // if the cart ID doesn't exist in the cookie, generate
            // a new ID

            if (context.Request.Cookies["CartId"] == null)
            {

                // generate a new GUID
                cartId = Guid.NewGuid().ToString();
                           // create the cookie object and set its value
                HttpCookie cookie = new HttpCookie("CartId", cartId);
                           // set the cookie's expiration date
                cookie.Expires = DateTime.Now.AddMinutes(2);
                    // set the cookie on the client's browser
                context.Response.Cookies.Add(cookie);
                         // return the CartID
                return cartId.ToString();
            }

            else   // check if the cart ID exists as a cookie
            {
                // return the id
                return cartId;
            }

        }          

    }

Here it saves cartId always null and not checking other statements

Second Attempt I added Current Context :

if (context.Request.Cookies["CartId"] == null)
            {
                HttpContext context = HttpContext.Current;

And context underlined with red says a local parameter named context cannot be declared in this scope because the name is used in an enclosing local scope.

newbie
  • 43
  • 1
  • 10
  • 2
    Put your code here instead of image. – Kaushik Maheta Nov 18 '15 at 11:43
  • "context" is the name of the parameter passed to your function. Change your variable name and the error will disappear. But this will probably not solve your problem because, context parameter is already reference equals HttpContext.Current (most likely). Your problem is, your cookie is not stored by the web browser – Oguz Ozgul Nov 18 '15 at 11:49
  • I can't find any tutorial or something that helps even here in stackoverflow. – newbie Nov 18 '15 at 11:51
  • Open developer tools of your browser and see in the request message if a cookie with name CartId is sent back to your server. If not, we discuss it. – Oguz Ozgul Nov 18 '15 at 11:53
  • No cookie isn;t stored by web browser, you are correct. But it remebers cart with 0 cartID and displays last choices on cart... fails cookie though.. – newbie Nov 18 '15 at 11:59
  • It does not remember the cookie. You are returning zero if the cookie does not exist – Oguz Ozgul Nov 18 '15 at 12:02

3 Answers3

0

Creating a cookies within a MVC Controller:

HttpCookie cookie = new HttpCookie("Cookie");
cookie.Value = "Hello Cookie! CreatedOn: " + DateTime.Now.ToShortTimeString();
this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);

Check & Read a cookie within a MVC Controller:

if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Cookie"))
{
    HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Cookie"];
...

The Cookies.AllKeys.Contains() can replace your null check.

How to you call your method? What is the value of context?

The MSDN Documentation about Cookies can be found here...

Marc
  • 4,715
  • 3
  • 27
  • 34
  • well look here: public static ShoppingCart GetCart(HttpContextBase context) { var cart = new ShoppingCart(); cart.ShoppingCartId = cart.GetCartId(context); return cart; } – newbie Nov 18 '15 at 12:05
  • and public class ShoppingCartController : Controller { ApplicationDbContext storeDB = new ApplicationDbContext(); // // GET: /ShoppingCart/ public ActionResult Index() { var cart = ShoppingCart.GetCart(this.HttpContext); // Set up our ViewModel var viewModel = new ShoppingCartViewModel { CartItems = cart.GetCartItems(), CartTotal = cart.GetTotal() }; // Return the view return View(viewModel); } – newbie Nov 18 '15 at 12:09
0

Working with cookie in Legacy Asp.net was good, As you are developing application using MVC design pattern, Here we have other important concept to manage state.

Few are listed below:-

tempdata

viewdata

viewbag

And you can get explanation here

Community
  • 1
  • 1
Chetan Sharma
  • 334
  • 2
  • 11
  • So.... how you can manage users to remember their cart and allow anonymous and registered users to order with viewbag?and remeber users cart with unique id without GuId? I know what these things do... you just throw things and not helping out... – newbie Nov 18 '15 at 12:14
  • But I think this will not solve his problem of storing the cart Id for two minutes on the client. – Oguz Ozgul Nov 18 '15 at 12:17
  • Saving cart/product and user details in cookie is not the good idea, better you should use any server side state management technique like state server or sql server etc. – Chetan Sharma Nov 18 '15 at 12:17
  • Even you can store very small amount of data in cookie, and some one do login in same system, they can also view same cart item, as other did (like in some cafe), Better to be handle via sessionID and state server. – Chetan Sharma Nov 18 '15 at 12:19
  • 2 minutes was just for checking and testing if it runs... can you explain Cheran Sharma your concept a little bit? – newbie Nov 18 '15 at 12:20
  • 1
    See, Some one using system in computer café and added some item in cart, So cookie will be there. Now in some time (Just after) some one else opened site, he can see same items in cart, that he is not added. So for every anonymous user cart should be unique. – Chetan Sharma Nov 18 '15 at 12:24
  • Note: sessions are maintained through http only cookies as well. If someone has left the browser open (not even the one he enters your site, any instance of the same browser) and another one comes to that pc and opens your site, he will continue with the other persons session as well – Oguz Ozgul Nov 18 '15 at 12:28
  • 1
    It is only when browser memory not supporting cookie saving in client machine. Think for all scenario buddy. No one saving client and product info in client machine or via cookie, that will increase URL length. Try debug any shopping site first. – Chetan Sharma Nov 18 '15 at 12:32
  • This is why, starting with IE 9 we have the InPrivate browsing option which will not share the received cookies with other instances of IE – Oguz Ozgul Nov 18 '15 at 12:32
  • 1
    session time out will be there for open browser, but cookie will be there, go through all the scenario buddy. – Chetan Sharma Nov 18 '15 at 12:33
  • Of course, it is better to achieve this with session. What I'm talking about is, since Http is a stateless communications protocol, being able to have a unique session for a client is only possible by using the HttpOnly cookie, or by passing the session id in the query string – Oguz Ozgul Nov 18 '15 at 12:34
  • @chetan-sharma. You can set expiration for a cookie. He is already setting it to two minutes.. – Oguz Ozgul Nov 18 '15 at 12:36
  • So suppose you are at your home and in your pc you order 3 items.... if you go on other device and suppose it is your laptop or tablet cart will display the same items? 3 items? the cookie isn't been saved on disk? – newbie Nov 18 '15 at 12:37
  • No, it will not display any of the items. For that, you should authenticate the user first. And if you can authenticate the person, you don't need any cookie, you don't even need the session, since you know who he is, you can store the cart of the known user in the DB – Oguz Ozgul Nov 18 '15 at 12:38
  • Your users are anonymous. Right? – Oguz Ozgul Nov 18 '15 at 12:39
  • Then, you need to implement your cart to be stored in the session, but this requires that you can access the session for the users, and this requires that, the Asp.net session cookie is accepted and sent back by the browser. Did you, when you check with the developer tools, have seen the session id cookie in the request? – Oguz Ozgul Nov 18 '15 at 12:44
  • Well session was working.... I am talking about session that lasts until browser close. If user open browser again cart is null because session takes space of my app( in case I made session lasting for 1 day for example).... – newbie Nov 18 '15 at 12:50
0

The value for the HttpOnly property of HttpCookie is "false" by default

This means you ask the browser to store your cookie on the disk

Change this to "true" before adding the cookie to the response. A note here, the client cookie will be lost if he closes all the instances of the browser.

If this does not help, you should add a privacy policy to your web site

try this, and if http only does not help, we can go for the p3p privacy policy solution

Oguz Ozgul
  • 6,809
  • 1
  • 14
  • 26
  • I did in the Web.config file. In the section and again it goes null in CartID and cookie isn't working and not saved. – newbie Nov 18 '15 at 12:26
  • p3p (privacy policy). This will almost guarantee that the browsers will accept your cookies. Did you try HttpOnly = true? – Oguz Ozgul Nov 18 '15 at 12:31
  • I think it is like this I mentioned above....I added in system.web section of web.config file this : .... that's it right? That's what you mean? – newbie Nov 18 '15 at 12:39
  • Yes, sorry I missed that first comment of yours. – Oguz Ozgul Nov 18 '15 at 12:42