你应该只使用FormsAuthentication设置饼干:
FormsAuthentication.SetAuthCookie(theUserID, true);
然后拿回来:
string userId = HttpContext.Current.User.Identity.Name;
如果你担心安全,你只能使用安全cookie考虑(你只能够读取通过https该cookie) 。
有一个相关的帖子更多关于这方面的信息:Manual Access control in ASP .Net
更新:根据您的意见,你不认为你可以设置自定义登录表单的窗体身份验证cookie。所以我创建了一个空白的ASP.NET 4项目,我创建了一个自定义登录名 - 它将登录任何未经身份验证的用户。这里有三个部分:
的web.config
(你的项目应该有类似的东西,因为你有你的网站上的表单,人们登录):
<authentication mode="Forms"></authentication>
代码前:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="emptyWebApp._default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Username: <asp:Label ID="_username" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
后面的代码:
using System;
using System.Web;
using System.Web.Security;
namespace emptyWebApp
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
_username.Text = HttpContext.Current.User.Identity.Name;
}
else
{
_username.Text = "Not logged in";
FormsAuthentication.SetAuthCookie("CookieMan", true);
}
}
}
}
正如你所看到的,你可以设置一个验证在您自己的自定义身份验证功能中使用FormsAuthentication.SetAuthCookie
作为诱导cookie,即使这样做也是非理性的。
在这种情况下,他们第一次点击该页面时,将显示Username: Not logged in
,然后它会以“CookieMan”的身份登录。刷新页面将显示Username: CookieMan
。
我使用**自定义登录**表单,那么为什么你建议我FormsAuthentication? – osmiumbin 2013-02-17 20:20:08
...因为它有效?这将设置一个cookie来保存当前登录的用户信息。尝试一下。尽管我可能会存储电子邮件而不是userId。我在自定义角色提供程序的自定义登录中使用了它。 – MikeSmithDev 2013-02-17 20:22:17
@osmiumbin增加了一个例子。希望你会玩这个,看看它是一个管理你的认证cookie的好方法。 – MikeSmithDev 2013-02-17 22:00:51