2
在MVC5中,我通過覆蓋控制器中的Initialize
方法將當前登錄用戶的ID初始化爲私有文件。獲取當前在控制器構造函數中登錄的用戶ID ASP.NET 5 MVC6
public class BaseControllerConstructor: Constructor
{
protected UserProfile _currentUserProfile;
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
if (User.Identity.IsAuthenticated)
{
_currentUserId = User.Identity.GetUserId();
_currentUserProfile = LoadUserProfile(_currentUserId);
}
}
}
在MVC6控制器中沒有Initialize
。
當我嘗試在構造函數中獲取當前登錄用戶的ID時,User
和HttpContext
是null
。
public BaseControllerConstructor()
{
// HttpContext is null
string _currentUserId = HttpContext.User.GetUserId();
_currentUserProfile = LoadUserProfile(_currentUserId);
}
我該如何在MVC6中實現這一目標?特別是:如何獲取當前登錄用戶的用戶ID,並在BaseControllerConstructor
中初始化_currentUserId
?
然後在控制器的動作只要致電:
class Controller: BaseControllerConstructor
{
public ActionResult Action()
{
foo(_currentUserProfile);
}
}
更新:我解決了這個使用依賴注入。請看下面的答案。