在asp.net 4.5中,Cookie域始终为空

时间:2014-07-13 11:58:55

标签: asp.net cookies .net-4.5

我总是在读取时获取cookie.Domain的空值。

您似乎只能设置Cookie域,但从未阅读过。

这是正确的行为吗?


以下是一个例子:

<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>

代码背后:

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

我的Web.Config包含:

<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>

当我运行上面的演示并单击“设置Cookie”按钮时,将按预期在浏览器中设置以下cookie:

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

当我尝试使用上面的Read Cookie函数读取cookie时,它会读取值,但域始终为空:

domain: ; value: The cookie was set

1 个答案:

答案 0 :(得分:1)

根据我的判断,cookie域值只能写在.net