In this article I will explain with an example, how to get Session ID in ASP.Net Core MVC.
Note: For enabling and configuring Session in ASP.Net Core, please refer my article Enable Session in ASP.Net Core.
 
 
Namespaces
You will need to import the following namespace.
using Microsoft.AspNetCore.Http;
 
 

Controller
The Controller consists of the following two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for getting the Session ID
When the Get SessionId Button is clicked, SetSession Action method is executed which saves the value to the Session using the SetString method.
Then the Session ID is retrieved from HttpContext.Session property and set in TempData object.
Finally, the Action is redirected to the Index Action method.
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public IActionResult SetSession()
    {
        //Set value in Session object.
        HttpContext.Session.SetString("Name", "Mudassar Khan");
 
        //Get SessionID inside Controller.
        TempData["SessionID"] = HttpContext.Session.Id;
 
        return RedirectToAction("Index");
    }
}
 
 
View
The View consists of an HTML Form with following ASP.Net Tag Helpers attributes.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of a Submit Button i.e. for getting Session ID.
The Submit Button has been set with a FormAction attribute which specifies the Action method which will be called when the Submit Button is clicked.
When the Get SessionId button is clicked, the Session ID value from the TempData object is displayed.
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <form method="post" asp-controller="Home">
        <input type="submit" formaction="@Url.Action("SetSession")" value="Get SessionId"/>
        <hr/>
        SessionId: @TempData["SessionID"]
    </form>
</body>
</html>
 
 
Screenshot
Get Session ID in ASP.Net Core
 
 
Downloads