CsitLabs
  • CSIT Labs
  • 1st Semester
    • Digital Logics
      • Lab 1
      • Lab 2
      • Lab 3
      • Lab 4
      • Lab 5
      • Lab6
    • IIT
    • Physics Lab Report Formet
  • 2nd Semester
    • Algorithms used in Discrete Structure class
    • Microprocessor
      • 8085 Microprocessor
        • Arithmetic and Logical Instruction Set
        • Branching Instruction Set
        • Data Transfer and Instruction Set
        • Multiply, Divide and Memory Block Operations
        • Rotate Instruction Set
        • Subroutine, Stack and BCD Conversion](Subroutine_Stack_BCD_Conversion
      • 8086 Microprocessor
        • Basic Arithmetic
        • Practice Programs for 8086 Microprocessor
        • String Processing
    • Object Oriented Programming using C++
      • File Access Pointers
      • Standard Exceptions in C++
    • Statistics-I
  • 3rd Semester
    • Computer Architecture
      • Practical labs
    • Computer Graphics
      • Practial
      • Simulation of Two Dimensional Transformation
      • Scan Conversion Algorithm
    • Data Structures and Algorithms
      • Array methods (Introduction)
      • Stack
      • Queue
      • Recursion
      • Linked List
      • Sorting Algorithms
      • Searching and Hashing Algorithms
      • Trees and Graphs
      • Lab practice
    • Numerical Method Labs
      • Lab practice
    • Statistics-II Labs
      • Confidence interval of mean assuming normal distribution
      • One Sample T test
      • Two Sample T test
      • Regression Analysis
      • Two Sample T test
      • Design_of_Experiment
        • CRD (Completely Randomized Design)
        • RBD (Randomized Block Design)
        • RBD (Randomized Block Design)
      • Non-parametric_test
        • Binomial Test
        • Cochran Q test
        • Kolmogorov-Smirnov one sample test
        • Run test
        • Friedman-F_test
          • Friedman F test
          • Friedman F test
        • Kruskal-Wallis-H_test
          • Kruskal Wallis H test
          • Kruskal Wallis H test
        • Mann-Whitney-U_test
          • Mann Whitney U test
          • Mann Whitney U test
        • Median_test
          • Median Test
          • Median Test
        • Wilcoxon-Matched-pair_signed_rank_test
          • Wilcoxon Matched pair signed rank test
          • Wilcoxon Matched pair signed rank test
  • 4th Semester
    • Artificial Intelligence
    • Computer Networks
      • Networking commands in CMD
    • DBMS Lab
    • Operating System
      • Linux Commands
    • Theory of Computation
      • Lab 1 (DFA)
      • Lab 2 (NFA)
  • 5th Semester
    • Cryptography
    • Design and Analysis of algorithms
    • Multimedia
      • Animation Creation with Blender
      • FL Studio - Simple Effect Creation
      • Macromedia FreeHand - Logo Creation
      • Audio Mixing
      • Adobe Photoshop - ID Card Creation
      • Video Editing with Adobe Premiere Pro
    • Simulation & Modeling
      • Lab 1: Random Number Generation
    • System Analysis and Design
    • Web Technology
      • Lab Assignment – I (HTML)
      • Lab Assignment – II (CSS)
      • Lab Assignment – III (JavaScript and XML)
      • Lab Assignment – IV (PHP)
      • Web Technology
        • php
          • Database connection using PHP and MySQL
          • Login form
          • Login form
  • 6th Semester
    • Compiler Design and Construction
    • NET Centric Computing
      • Class Codes
        • Authentication and Authorization in ASP.NET
        • C# Basics
      • Lab Codes
        • Practical 1
        • Practical 2
          • Number Operations Web App
          • User Registration Form
          • User Registration Console App
        • Practical 3
          • Authentication and Authorization (Claims, Roles and Policies)
          • Client side state management in ASP.NET
          • Entity Framework Core
          • Form Validation
            • React form validation
          • HTML Tag Helpers
          • MVC demonstration
          • Razor Syntax
          • Server Side State Management in ASP.NET
      • Self Projects
        • Do while programs
        • Role playing game battle challenge
        • Project overview
        • Authentication
          • wwwroot
            • lib
              • jquery-validation
                • The MIT License (MIT)
  • 7th Semester
    • Advanced Java Programming
      • Class Codes
        • Unit1-6&8
          • javafx-sdk-21.0.1
            • legal
              • javafx.graphics
                • Independent JPEG Group (IJG) JPEG v9e
                • Mesa 3-D Graphics Library v21.0.3
              • javafx.media
                • Microsoft DirectShow Samples v156905
                • GNU Glib v2.72.0
                • GStreamer v1.20.1
                • LibFFI v3.4.4
              • javafx.web
                • IBM International Components for Unicode (ICU4C) v73.1
                • xmlsoft.org: libxml2 v2.10.4
                • xmlsoft.org: libxslt v1.1.35
                • WebKit Open Source Project: WebKit v616.1
          • src
            • main
              • java
                • Unit 1: Programming in Java
                  • 2. Concepts and Topics
                • Unit 2: User Interface Components with Swing
                • Unit 3: Event Handling
                • Unit 4: Database Connectivity
                • Unit 5: Network Programming
                • Unit 6: GUI with JavaFX
        • Unit7
          • src
            • main
              • webapp
                • index
      • Lab Codes
        • Lab
          • src
            • main
              • java
                • Practical 1
                • Practical 2
                • Practical 3
                • Practical 4
                • Practical5
    • Data warehouse and Data mining
  • docs
    • Contributor Covenant Code of Conduct
Powered by GitBook
On this page
  • Session State
  • Important things to consider while working with Session state
  • Creating Session State using MVC
  • TempData
  • Creating TempData using MVC
  • HttpContext
  • Creating HttpContext

Was this helpful?

  1. 6th Semester
  2. NET Centric Computing
  3. Lab Codes
  4. Practical 3

Server Side State Management in ASP.NET

Server-side state management is a technique used to store information about the state of a web page on the server. This information can be accessed and modified by the server-side code, allowing the web application to maintain the state of the page across multiple requests.

HTTP is a stateless protocol. So, HTTP requests are independent messages that don't retain user's values or app states.

State can be managed in the application using server approaches as:

  • Session state: Session state is used to store information about the user's session on the server. This information is associated with a unique session ID that is sent to the client in a cookie or as part of the URL. Session state can be used to store user-specific information, such as shopping cart items or user preferences.

  • TempData: TempData is a dictionary object that is used to store data between requests. TempData is used to pass data from one action method to another action method in the same controller or in a different controller. TempData is useful when you want to pass data between actions but don't want to persist the data in the session.

  • HttpContext: The HttpContext object is used to store information about the current HTTP request and response. The HttpContext object provides access to the request and response objects, as well as other information about the current request, such as the user's IP address and browser type.

Session State

Session state is an ASP.NET Core mechanism to store user data while the user browses the application. It uses a store maintained by the application to persist data across requests from a client. We should store critical application data in the user's database and we should cache it in a session only as a performance optimization, if required.

ASP.NET Core maintains the session by providing a cookie to the client that contains a session ID. The browser sends back the cookie to the application in each request. The application uses the session ID to fetch the session data.

Important things to consider while working with Session state

  • A session cookie is specific to the browser session.

  • When a browser session ends, it deletes the session cookie.

  • If the application receives a cookie for an expired session, it creates a new session that uses the same session cookie.

  • An application doesnot retain empty session data.

  • The application retains a session for a limited time after the last request. The app either sets the session timeout or uses the default value of 20 minutes.

  • Session state is ideal for storing user data that are specific to a particular session but doesnot require permanent storage across sessions.

  • An application deletes the data stored in session either when we call ISession.Clear or when the session expires.

  • There is no default mechanism to inform the application that a client has closed the browser or deleted the session cookie or it is expired.

Creating Session State using MVC

  1. First, we need to configure the Program.cs file to use the session state.

     builder.Services.AddSession();
    
     // other configurations
     app.UseSession();
  2. Then, let's add a controller for the session state.

    public class SessionController : Controller
     {
         public IActionResult Index(string Name)
         {
             HttpContext.Session.SetString("Name", Name);
             return View();
         }
    
         public IActionResult Get()
         {
             string name = HttpContext.Session.GetString("Name");
             ViewBag.Name = name; // Add the name to the ViewBag
             return View();
         }
     }
  3. Finally, let's create the views for the controller.

    • Index.cshtml

      <form asp-action="Index" method="post">
        <input type="text" name="Name" />
        <input type="submit" value="Submit" />
      </form>
    • Get.cshtml

      <h1>Welcome, @ViewBag.Name</h1>

TempData

  • TempData is a dictionary object that is used to store data until it is read.

  • It is used to pass data from one action method to another action method in the same controller or in a different controller.

  • We can use Keep() and Peek() methods to examine the data without deletion.

  • TempData is useful when we require the data for more than a single request.

  • We can access them from controllers and views.

  • TempData is implemented by TempData providers using either cookies or session state.

Creating TempData using MVC

  1. First, let's add a controller for TempData, for one-time storage.

     public IActionResult Index()
     {
         TempData["Name"] = "John Doe";
         return View();
     }

    In this code, we are storing the name "John Doe" in TempData.

    public IActionResult Second()
    {
        string name = TempData["Name"] ?? null; // Get the name from TempData or null
        ViewBag.Name = name; // Add the name to the ViewBag
        return View();
    }

    Then, in the second action method, we are retrieving the name from TempData and storing it in the ViewBag.

    public IActionResult Third()
    {
        string name = TempData["Name"] ?? null;
        ViewBag.Name = name;
        return View();
    }

    Here, we are retrieving the name from TempData in the third action method. But, since TempData is a one-time storage, the name will be deleted after it is read in the second action method.

  2. For persistent storage, we can use the Keep() method or Peek() method.

  • TempData.Keep()/TempData.Keep(string key): Marks the specified key in TempData to be retained for another request. If the key is not specified, all keys are retained.

  • TempData.Peek(string key): Returns the value associated with the specified key in TempData without marking the key for deletion.

    • Using Keep() method

      public IActionResult Second()
      {
          string name = TempData["Name"] ?? null;
          TempData.Keep("Name"); // Keep the name in TempData
          ViewBag.Name = name;
          return View();
      }
      • Using Peek() method

      public IActionResult Third()
      {
          string name = TempData.Peek("Name") ?? null;
          ViewBag.Name = name;
          return View();
      }

HttpContext

  • A HttpContext object holds information about the current HTTP request and response.

  • It provides access to the request and response objects, as well as other information about the current request, such as the user's IP address and browser type.

  • The important point is, whenever we make a new HTTP request or response then the HttpContext object is created.

  • Each time it is created, it creates a server current state of a HTTP request and response.

  • It can hold information like Request, Response, Server, Session, Item, Cache, User's information like authentication and authorization and much more.

  • As the request is created in each HTTP request, it ends too after the finish of each HTTP request or response.

Creating HttpContext

  1. Adding Session State using HttpContext

     public IActionResult Index()
     {
         HttpContext.Session.SetString("Name", "John Doe");
         return View();
     }

    In this code, we are storing the name "John Doe" in the session.

    public IActionResult Get()
    {
        string name = HttpContext.Session.GetString("Name");
        ViewBag.Name = name; // Add the name to the ViewBag
        return View();
    }
  2. Access the current URL using HttpContext.

    protected void Page_Load(object sender, EventArgs e)
     {
         string url = HttpContext.Current.Request.Url.ToString();
         Response.Write("The current URL is: " + url);
     }
  3. Access the user's IP address using HttpContext

    protected void Page_Load(object sender, EventArgs e)
     {
         string ip = HttpContext.Current.Request.UserHostAddress;
         Response.Write("Your IP Address is: " + ip);
     }
PreviousRazor SyntaxNextSelf Projects

Last updated 8 months ago

Was this helpful?