你應該只使用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