Is this the reliable way to read and write ASP.NET cookie multiple subkeys? RRS feed

  • Question

  • User1167734619 posted

    This is my code. It seems to work ok.
    But I'm worried if it is reliable.

    sub put_cookie_string( cookie_value, subkeyName  )
    	If (Request.Cookies( PROGRAM_COOKIE_NAME) IS Nothing) Then			  
    		Response.Cookies( PROGRAM_COOKIE_NAME )( subkeyName ) = cookie_value
    		Response.Cookies( PROGRAM_COOKIE_NAME).Expires = DateTime.Now.addyears(50)
    		Dim aCookie As HttpCookie = Request.Cookies( PROGRAM_COOKIE_NAME )
    		aCookie.Values.Set( subkeyName, cookie_value )
    		aCookie.Expires = DateTime.Now.addyears(50)
    		Response.Cookies.Add( aCookie )
    	end if
    end sub
    function get_cookie_string( byval subkeyName  ) 
    	get_cookie_string = ""
    	If (Request.Cookies( PROGRAM_COOKIE_NAME) IsNot Nothing) Then
    		If (Request.Cookies( PROGRAM_COOKIE_NAME)( subkeyName) IsNot Nothing) Then
    			get_cookie_string = 	Request.Cookies( PROGRAM_COOKIE_NAME)( subkeyName )
    		End If
    	End If
    end function

    Monday, March 4, 2019 4:23 PM

All replies

  • User-1174608757 posted

    Hi doug@soft-factory.com,

    According to your code, sub put_cookie_string is used to check the cookie PROGRAM_COOKIE_NAME is null or not, if it is null then add , if it is not null , then its subkey and value will be covered. It seems no problem however you set the cookie time as 50 years,we normally  don't set the cookie as this , if you want store cookie permanently,I suggest you to write as below:

    Response.Cookies( PROGRAM_COOKIE_NAME).Expires = DateTime.MaxValue;

    Then for function get_cookie_string, this function has some problem.Since get_cookie_string is defined in the function ,you should return  get_cookie_string in the end ,else it is meaningless. You should write as below:

     Function get_cookie_string(ByVal subkeyName)
            get_cookie_string = ""
            If (Request.Cookies(PROGRAM_COOKIE_NAME) IsNot Nothing) Then
                If (Request.Cookies(PROGRAM_COOKIE_NAME)(subkeyName) IsNot Nothing) Then
                    get_cookie_string = Request.Cookies(PROGRAM_COOKIE_NAME)(subkeyName)
                    Return get_cookie_string
                End If
            End If
        End Function

    Best Regards

    Wei Zhang

    Tuesday, March 5, 2019 3:13 AM