George Filippakos
George Filippakos

Reputation: 16569

Cookie domain is always Empty in asp.net 4.5

I am always getting an empty value for cookie.Domain on read.

It seems that you can only ever set the cookie domain, but never read it.

Is this correct behaviour?


Here is an example:

<form id="form1" runat="server">
<div>
    <asp:Button ID="Button1" runat="server" Text="Set Cookie" />
    <asp:Button ID="Button2" runat="server" Text="Read Cookie" />
    <asp:Label ID="Label1" runat="server" Text="Output"></asp:Label>
</div>
</form>

Code behind:

Private _cookieName As String = "TestCookie"

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'create cookie:

    'Initialize FormsAuthentication
    'Reads the configuration and gets the cookie values and encryption keys for the given application
    FormsAuthentication.Initialize()

    Dim cookie As New HttpCookie(_cookieName)
    cookie.Domain = FormsAuthentication.CookieDomain
    cookie.Secure = FormsAuthentication.RequireSSL
    cookie.Value = "The cookie was set"
    cookie.Expires = Date.UtcNow.AddDays(1)
    Response.Cookies.Add(cookie)
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    'read cookie:
    Dim cookie As HttpCookie = Request.Cookies.Get(_cookieName)
    Label1.Text = "domain: " & cookie.Domain & "; value: " & cookie.Value
End Sub

My Web.Config contains:

<authentication mode="Forms">
  <!--Allows authorization across sub domains-->
  <forms cookieless="UseCookies" defaultUrl="/" loginUrl="~/login/" protection="All" slidingExpiration="false" path="/" ticketCompatibilityMode="Framework40" 
         requireSSL="false" timeout="129600" name=".DEMO" domain=".demo.lan" />
</authentication>

When I run the demo above, and click the Set Cookie button, the following cookie is being set in the browser as expected:

TestCookie=The cookie was set; expires=Mon, 14 Jul 2014 11:52:01 GMT; path=/; domain=.demo.lan

When I try to read the cookie using Read Cookie function above, it reads the value but the domain is always Empty:

domain: ; value: The cookie was set

Upvotes: 2

Views: 834

Answers (1)

George Filippakos
George Filippakos

Reputation: 16569

From what I can gauge , the cookie Domain value is Write only on .net

Upvotes: 2

Related Questions