問題描述
簡單的會員管理帳戶 (Simple Membership Admin Accout)
我正在開發我的第一個 ASP.Net MVC 4 應用程序,現在堅持使用一個簡單的用例。
我需要對一個用戶(管理員)進行身份驗證,以便他/她可以登錄到管理區域執行某些任務。雖然 ASP.Net 互聯網項目模板具有使用簡單成員資格的帳戶控制器,但這似乎比我實際需要的要多得多。例如,我真的不需要用戶註冊功能和用戶角色。我的要求相當簡單,只需在數據庫中存儲一個用戶,讓他可以選擇更新他的信息,如密碼、電子郵件等,並授予他訪問管理區域(管理控制器和操作)的權限。我想不通的是
- 對於這個簡單的場景,我的唯一選擇是簡單的會員資格還是其他asp.net會員資格提供者。
參考解法
方法 1:
You can build a custom method to grab the user and their stored role, then evaluate it in your controller. So, for instance:
public ActionResult GetAdminPage()
{
var loggedInUserName = HttpContext.User.Identity.Name;
var user = somesortofproviderlookupmethod(loggedInUserName);
// Assume user is a bool and is true
if (user)
{
return view("AdminPage");
}
}
The only thing I'm not sure of is whether or not HttpContext.User requires membership. Perhaps someone can shed some light. If so, perhaps you could send the username from the view, but then of course you're trusting the client. So how you are doing user authentication would change this answer somewhat.
Personally, I like membership. It's clean, easy, fast and can be scaled nicely if you end up having additional requirements. Doing something like this would be even easier with membership, since then you can actually use Roles.GetRolesForUser(); and only return the admin view if they contain the role you are looking for.