簡體   English   中英

ASP.NET核心標識中的基本控制器繼承

[英]Base Controller inheritance in ASP.NET Core identity

我剛開始在asp net core中開始我的第一個項目,並從.Net框架遷移。

我使用ASP.NET Core 2.1創建了一個新項目,並添加了Identity via

Right click on project -> Add -> Add scaffolded items

到我的項目。

首先,有些事讓我困惑。 所有用於標識的文件都移動到名為Identity和Manage部分文件的區域移動到Account文件夾。 最重要的是我沒有帳戶和管理控制器

我創建了一個名為BaseController的新空控制器:

public class BaseController : Controller
{
    private ApplicationDbContext _db { get; set; }

    public BaseController(ApplicationDbContext db)
    {
        _db = db;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (HttpContext.User.Identity.IsAuthenticated)
        {
            string userEmail = User.Identity.Name;                
            ViewBag.CurrentUser = _db.Users.Where(u => u.Email.Equals(userEmail)).FirstOrDefault();
        }

        base.OnActionExecuting(filterContext);
    }
}

在這個控制器中,我獲取登錄用戶並將其傳遞給ViewBag並在我的視圖中顯示它。

我有一個繼承自BaseControllerHomeController

public class HomeController : BaseController
{
    private UserManager<ApplicationUser> _userManager { get; set; }
    private readonly ApplicationDbContext _db;

    public HomeController(UserManager<ApplicationUser> userManager, 
                          ApplicationDbContext db) : base (db)
    {
        _userManager = userManager;
        _db = db;
    }

    public IActionResult Index()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}

這部分代碼工作正常,但是當我嘗試導航到Manage/IndexManage/ChangePassword我收到此錯誤,我不知道如何解決此問題。 此錯誤的原因是ViewBag為空,因為基本控制器操作永遠不會運行。

對不起,如果我的問題很簡單而且不專業

在asp.net core 2.1中,scaffold Identity使用Razor Pages而不是MVC結構,因此Identity區域中沒有控制器,您無法繼承控制器。 請參閱此處

由於它在區域內,您需要使用https://localhost:44367/Identity/Account/Manage/Indexhttps://localhost:44367/Identity/Account/Manage/ChangePassword來訪問Razor頁面。

此外,Razor Pages不支持ViewBag ,您可以使用ViewData ,請參閱此處

要為Razor Pages添加過濾器,您可以參考Razor頁面中的過濾器

public class BasePageModel : PageModel
{
    public override void OnPageHandlerExecuting(PageHandlerExecutingContext context)
    {
        //...
    }
}
public class IndexModel : BasePageModel
{
    public void OnGet()
    {
        //...
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM