Home > front end >  Get the user details from MS Graph and show it in navbar
Get the user details from MS Graph and show it in navbar

Time:12-05

I'm trying to show the current logged in user in navbar "Name , profile photo and phone number". in Home controller i used this to get the details

 public async Task<IActionResult> Profile()
        {
            try
            {
                var me = await _graphServiceClient.Me.Request().GetAsync();
                ViewData["Me"] = me;
                // Get user photo
                using (var photoStream = await 
              _graphServiceClient.Me.Photo.Content.Request().GetAsync())
                {
                    byte[] photoByte = ((MemoryStream)photoStream).ToArray();
                    ViewData["Photo"] = Convert.ToBase64String(photoByte);
                }
            }
            catch (System.Exception)
            {
                ViewData["Photo"] = null;
            }

            return View();
        }

Then pass the data to _loginPartial by ViewData, but when i navigate to another page the details on _loginPartial navbar disappear and only show when i call the home controller again

 @var user = ViewData["me"] as Microsoft.Graph.User;
 @if (User.Identity?.IsAuthenticated == true)
{           

            <li >
                @if(user != null){
                    <span > Hello @user.DisplayName!</span>
                    <span > @user.BusinessPhones.FirstOrDefault()</span>  
                }
            </li>
            if (ViewData["photo"] != null)
                    {
                    <img style="margin: 5px 0; width: 50px; border-radius:50%;" 
                     src="data:image/jpeg;base64, @ViewData["photo"]" />   
                    }
                    else
                    {
                    <img style="margin: 5px 0; width: 50px; border-radius:50%;" 
                     src="~/img/defaultprofileicon.jpg" />
                    }

Is there any way to get user details on Program.cs as i use .net core mvc 6 and share this details across the app so they will appear in navbar in every page, Thank for help

CodePudding user response:

but when i navigate to another page the details on _loginPartial navbar disappear

Below is a demo to use session to pass the string to appear in navbar in every page , you can refer to it.

1.Register IHttpContextAccessor and session in Program.cs

builder.Services.AddSession();
builder.Services.AddHttpContextAccessor();
...
app.UseSession();

2.In the controller, set a session variable:

 HttpContext.Session.SetString("Photo", "p1");

3.2.In _loginPartial.cshtml, inject IHttpContextAccessor implementation and use it to get the HttpContext and Session object from that.

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
...
@HttpContextAccessor.HttpContext.Session.GetString("Photo")

result: enter image description here

  • Related