我需要根據用戶ID來控制對我的控制器編輯方法的訪問權限,即只有該用戶可以訪問創建該特定數據的編輯方法。 用戶標識存儲在表EmpProfile UserID列中,並希望將當前登錄用戶與存儲的用戶標識進行比較,並允許在此基礎上進行訪問。 我的自定義授權屬性代碼爲:如何通過比較存儲在表中的用戶標識和Asp.net MVC 5中的當前用戶標識來創建自定義授權屬性?
public class AuthorizeAuthorAttribute : AuthorizeAttribute
{
RecruitDB mydb = new RecruitDB(); // My Entity
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
return false;
}
string CurrentUser = httpContext.User.Identity.GetUserId().ToString(); // Current User ID(Converted to string)
var userName = from m in mydb.EmpProfiles //Calling method to get UserID from EmpProfile.UserID Column
where m.UserID == CurrentUser
select m.UserID;
string my = userName.ToString(); //Converting to string
if (CurrentUser.Contains(my)) //Comparing
{
return true;
}
else
{
return false;
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
控制器代碼:
[AuthorizeAuthor]
public ActionResult Edit(int? id)
{
}
但通過將授權我總是定向到登錄頁面。 同樣當用戶與作者相同時。
我不認爲在屬性邏輯應該是「重」(例如通過執行數據庫命中)。最初的授權屬性僅比較用戶的auth cookie中的數據,這是快速的內存中邏輯。通過在屬性中隱藏昂貴的代碼,您可以將應用程序邏輯的複雜性隱藏給其他開發人員。 – Dai
通過向我的操作添加[Authorize(User =「SomeUser」)],只允許特定的硬編碼用戶輸入。但是用戶如何創建數據只能得到授權。因爲它當前的用戶ID和數據創建者用戶ID應該匹配。很像站點用戶儀表板只能由用戶創建它訪問。 MVC是否提供這種授權?請指教。 – Fahad