Session & State Management

HTTP is a stateless protocol. By default, HTTP requests are independent messages that don't retain user values. In ASP.NET Core, state can be stored using several approaches.

Storage approachStorage mechanism

HTTP cookies. May include data stored using server-side app code.

HTTP cookies and server-side app code

HTTP cookies or session state

HTTP query strings

HTTP form fields

Server-side app code

Server-side app code

TempData

This property stores data until it's read in another request. The Keep(String) and Peek(string) methods can be used to examine the data without deletion at the end of the request. TempData is:

  • Useful for redirection when data is required for more than a single request.

  • Implemented by TempData providers using either cookies or session state.

public class CreateModel : PageModel
{
    private readonly RazorPagesContactsContext _context;

    public CreateModel(RazorPagesContactsContext context)
    {
        _context = context;
    }

    public IActionResult OnGet()
    {
        return Page();
    }

    [TempData]
    public string Message { get; set; }

    [BindProperty]
    public Customer Customer { get; set; }

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        _context.Customer.Add(Customer);
        await _context.SaveChangesAsync();
        Message = $"Customer {Customer.Name} added";

        return RedirectToPage("./IndexPeek");
    }
}

Last updated