如何获取用户的当前ID传递给_Layout ASP.NET Core? [英] How to get the current Id of a user to pass to _Layout ASP.NET Core?

查看:53
本文介绍了如何获取用户的当前ID传递给_Layout ASP.NET Core?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将当前用户的ID传递到_Layout主页.

I need to pass the Id of the current user to the _Layout master page.

必须将其传递到"asp-route-id"

It must be passed to where "asp-route-id"

<a class="nav-link text-dark" asp-controller="Account" asp-action="MyPersonalCabinet" asp-route-id="HERE">My Cabinet</a>

这是方法:

public async Task<IActionResult> MyPersonalCabinet(string id)
{
    var user = await _userManager.FindByIdAsync(id);
    var userId = _userManager.GetUserId(HttpContext.User);
        
    if (user != null && userId == id)
    {
        return View(user);
    }

    return NotFound();
}        

使用 var userId = _userManager.GetUserId(HttpContext.User); ,我在方法中获取当前ID.我该怎么做才能将此ID传递给_Layout

With var userId = _userManager.GetUserId (HttpContext.User); I get the current id in the method. How do I do something like this to pass this Id to _Layout

我试图用ViewBag提出一些建议,但没有成功

I tried to come up with something with ViewBag but it didn't work

推荐答案

您可以尝试在布局中注入userManager.

You can try injecting userManager in the layout.

@using Microsoft.AspNetCore.Identity
@inject UserManager<ApplicationUser> userManager

然后检索ID

<p>@{var user = userManager.GetUserAsync(User);
           var userId = user.Id;} </p>

这篇关于如何获取用户的当前ID传递给_Layout ASP.NET Core?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆