How to get user logged in to the view?

Asked

Viewed 363 times

2

I need to get the user who is logged in to my application, I did the example below but it does not work.

On my Nav tag I used the import Asp.net core and @inject

      <nav class="site-menu ">


        <ul>

            <li>
                <a href="shop-grid-ls.html"><span>Vendedores</span></a>

            </li>

            <li>
                <a href="shop-grid-ls.html"><span>Clientes</span></a>

            </li>

            <li>
                <a href="shop-grid-ls.html"><span>Produtos</span></a>

            </li>

            <li>
                <a href="shop-grid-ls.html"><span>Vendas</span></a>

            </li>

            <li>
                <a href="shop-grid-ls.html"><span>Relatórios</span></a>

            </li>
        </ul>

        <div id="NomeUsuarioLogado"></div> <!-- Importação aspnetcore e httcontextaccessor-->
        @using Microsoft.AspNetCore.Http
        @inject IHttpContextAccessor HttpContextAccessor

    </nav>

The second step is to create a Javascript function that catches the logged in user.

<script>
    function CarregaUsuarioLogado() {

        var nome = '@HttpContextAccessor.HttpContext.Session.GetString("NomeUsuarioLogado")'



        if (nome != "") {

            var divNome = document.getElementById("NomeUsuarioLogado");
            divNome.innerHTML = "Olá " + nome;
            divNome.style = "color:#000000; padding-top: 15px;";

        } else {
            //window.location.href = '../Home/Login';
        }
    }
</script>

and last on my tag

onload="CarregaUsuarioLogado()

<body onload="CarregaUsuarioLogado()">

  • You are using Identity?

1 answer

0


If you are using Identity just do so:

Na View

@using Microsoft.AspNetCore.Identity;

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager


//DIV onde vai aparecer o nome do usuário logado
<div>@UserManager.GetUserName(User)</div>


//OU

<div>@User.Identity.Name</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.