@Royden, based on my test, I reproduced the problem that I always get null Session Value. I did some search; it may be due to the version changing. I recommend that you could use Cookie to replace Session, which is more coinvent.
Please try the following Changes.
Asp.net MVC (.NET Framework):
Place the ViewBag.UserName in index.html
<section class="row" aria-labelledby="aspnetTitle">
<h1 id="title">ASP.NET</h1>
<p>My Name is @ViewBag.UserName</p>
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var sessionValue = "JohnDoe";
// Store a value in the session
Session["UserName"] = "JohnDoe";
// In a controller or action in the MVC app
var cookie = new HttpCookie("SharedSession", sessionValue)
{
HttpOnly = true, // Secure it to prevent client-side JavaScript access
Expires = DateTime.Now.AddMinutes(30), // Set expiration for the session
Domain = "localhost" // Set to the shared domain for subdomains
};
Response.Cookies.Add(cookie);
ViewBag.UserName = sessionValue;
return View();
}
}
ASP.NET Core MVC (.NET):
Place the ViewBag.UserName in index.html
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core </a>.</p>
<p>My Name is @ViewBag.UserName</p>
</div>
Controller:
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
var sharedSession = Request.Cookies["SharedSession"];
if (sharedSession != null)
{
// Use the session value
var sessionValue = sharedSession;
ViewBag.UserName = sessionValue;
}
return View();
}
}
Please run your asp.net mvc(.NET Framework) first, then run your asp.net core mvc, you will see the following tested result:
Hope it could help you.
Best Regards,
Jack
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.