In this article I will explain with an example, how to destroy, delete or remove Session objects in ASP.Net Core MVC.
Namespaces
You will need to import the following namespace.
using Microsoft.AspNetCore.Http;
Controller
The Controller consists of the following three Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for setting the Session object
When the Set Session Button is clicked, SetSession Action method is executed which saves the value to the Session using the SetString method.
Finally, the Action is redirected to the Index Action method.
Action method for deleting the Session object
When the Remove Session Button is clicked, DeleteSession Action method is executed which removes the Session object using its Key using the Remove method.
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");
return RedirectToAction("Index");
}
[HttpPost]
public IActionResult DeleteSession()
{
//Delete the Session object.
HttpContext.Session.Remove("Name");
return RedirectToAction("Index");
}
}
View
Inside the View, the IHttpContextAccessor Interface object is injected in order to access the Session and its functions inside the 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 two Submit Buttons i.e. for Setting Session and Deleting Session.
Each 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 Set Session button is clicked, the value from the Session object is displayed using the GetString method.
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor Accessor
@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" id="btnSet" formaction="@Url.Action("SetSession")" value="Set Session"/>
<input type="submit" id="btnRemove" formaction="@Url.Action("DeleteSession")" value="Remove Session"/>
<hr/>
Session: @Accessor.HttpContext.Session.GetString("Name")
</form>
</body>
</html>
Screenshot
Downloads