2

I am storing full name of user in cookie after user successfully logs in with following code.

var res = await _signInManager.PasswordSignInAsync(suser.UserName, user.Password, user.Remember, false);
                if (res.Succeeded)
                {
                    Response.Cookies.Append("fullName", suser.FullName);
                    if (string.IsNullOrWhiteSpace(returnUrl))
                        return RedirectToAction("Dashboard", "User");
                    else
                        return Redirect(returnUrl);
                }

I want to read this value in _Layout page so that I can display full name in master page. According to solution mention in this post. I tried following sysntax in my _Layout page.

@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
@{ 
      ViewBag.FullName = HttpContextAccessor.HttpContext.Request.Cookies["fullName"];
}

But I am not getting any value in ViewBag.FullName. Am I doing something wrong here? How to read stored value in cookies in Views?

Community
  • 1
  • 1
Bhavesh Jadav
  • 695
  • 1
  • 13
  • 33

1 Answers1

1

I´ve done some tests to get the same result as yours.

The way I see it, you´re appending a new cookie value to the Response.Cookie and trying to access it in the Request.Cookies, so, the added value ("fullname") will only be available in the next request (after a redirect). If you try to access it in a View rendered at the same request that you set the cookie, the cookie value will be null.

I did the test with "return View()" and with "return RedirectToAction", only the second one worked.

I see that in your code you´re doing a redirect, I advice to debug it and see if the code is actualling entering in that line of code, if it is, go to that action that you are redirecting and, debugging it, see if the Request.Cookies are ok.

Regards.

dime2lo
  • 826
  • 8
  • 15