本文转自:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state

+

+

+

Session state

+

+

Warning

+

+

+

TempData

+

Cookie-based TempData provider (requires ASP.NET Core 1.1.0 and higher)

+

Copy
C#
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    // Add CookieTempDataProvider after AddMvc and include ViewFeatures.
    // using Microsoft.AspNetCore.Mvc.ViewFeatures;
    services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
}

+

+

Query strings

+

+

Post data and hidden fields

+

Cookies

+

+

HttpContext.Items

+

Cache

+

+

Configuring Session

+

  • Add any of the IDistributedCache memory caches. The IDistributedCache implementation is used as a backing store for session.
  • Call AddSession, which requires NuGet package "Microsoft.AspNetCore.Session".
  • Call UseSession.

+

+

Copy
C#
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        // Adds a default in-memory implementation of IDistributedCache.
        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromSeconds(10);
            options.CookieHttpOnly = true;
        });
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseSession();
        app.UseMvcWithDefaultRoute();
    }
}

+

+

+

Loading Session asynchronously

+

+

Implementation Details

+

+

Copy
C#
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    // Adds a default in-memory implementation of IDistributedCache.
    services.AddDistributedMemoryCache();

    services.AddSession(options =>
    {
        options.CookieName = ".AdventureWorks.Session";
        options.IdleTimeout = TimeSpan.FromSeconds(10);
    });
}

+

+

Setting and getting Session values

+

+

Copy
C#
public class HomeController : Controller
{
    const string SessionKeyName = "_Name";
    const string SessionKeyYearsMember = "_YearsMember";
    const string SessionKeyDate = "_Date";

    public IActionResult Index()
    {
        // Requires using Microsoft.AspNetCore.Http;
        HttpContext.Session.SetString(SessionKeyName, "Rick");
        HttpContext.Session.SetInt32(SessionKeyYearsMember, 3);
        return RedirectToAction("SessionNameYears");
    }
    public IActionResult SessionNameYears()
    {
        var name = HttpContext.Session.GetString(SessionKeyName);
        var yearsMember = HttpContext.Session.GetInt32(SessionKeyYearsMember);

        return Content($"Name: \"{name}\",  Membership years: \"{yearsMember}\"");
    }

+

Copy
C#
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

public static class SessionExtensions
{
    public static void Set<T>(this ISession session, string key, T value)
    {
        session.SetString(key, JsonConvert.SerializeObject(value));
    }

    public static T Get<T>(this ISession session,string key)
    {
        var value = session.GetString(key);
        return value == null ? default(T) : 
                              JsonConvert.DeserializeObject<T>(value);
    }
}

+

Copy
C#
public IActionResult SetDate()
{
    // Requires you add the Set extension method mentioned in the article.
    HttpContext.Session.Set<DateTime>(SessionKeyDate, DateTime.Now);
    return RedirectToAction("GetDate");
}

public IActionResult GetDate()
{
    // Requires you add the Get extension method mentioned in the article.
    var date = HttpContext.Session.Get<DateTime>(SessionKeyDate);
    var sessionTime = date.TimeOfDay.ToString();
    var currentTime = DateTime.Now.TimeOfDay.ToString();

    return Content($"Current time: {currentTime} - "
                 + $"session time: {sessionTime}");
}

Working with HttpContext.Items

+

+

Copy
C#
app.Use(async (context, next) =>
{
    // perform some verification
    context.Items["isVerified"] = true;
    await next.Invoke();
});

+

Copy
C#
app.Run(async (context) =>
{
    await context.Response.WriteAsync("Verified request? " + context.Items["isVerified"]);
});

+

+

Application state data

+

  1. Define a service containing the data (for example, a class named MyAppData).

+

Copy
C#
public class MyAppData
{
    // Declare properties/methods/etc.
}
  1. Add the service class to ConfigureServices (for example services.AddSingleton<MyAppData>();.
  2. Consume the data service class in each controller:

+

Copy
C#
public class MyController : Controller
{
    public MyController(MyAppData myService)
    {
        // Do something with the service (read some data from it, 
        // store it in a private field/property, etc.
    }
    }
}

Common errors when working with session

  • "Unable to resolve service for type 'Microsoft.Extensions.Caching.Distributed.IDistributedCache' while attempting to activate 'Microsoft.AspNetCore.Session.DistributedSessionStore'."

    Commonly caused by not configuring at least one IDistributedCache implementation. See Working with a Distributed Cache and In memory caching for more information

+

Additional Resources

相关文章:

  • 2021-09-08
  • 2021-09-11
  • 2022-01-19
  • 2021-08-11
  • 2022-12-23
  • 2022-01-03
  • 2021-08-22
  • 2021-12-09
猜你喜欢
  • 2021-07-07
  • 2021-11-23
  • 2018-02-13
  • 2021-08-10
  • 2022-02-12
  • 2021-06-26
相关资源
相似解决方案