ارتقاء به ASP.NET Core 1.0 - قسمت 16 - کار با Sessions
نویسنده: وحید نصیری
تاریخ: ۱۳۹۵/۰۴/۳۱ ۱۱:۴۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
app.Use(async (context, next) =>
{
context.Items["isVerified"] = true;
await next.Invoke();
}); app.Run(async (context) =>
{
await context.Response.WriteAsync("Verified request? " + context.Items["isVerified"]);
}); {
"dependencies": {
//same as before
"Microsoft.AspNetCore.Session": "1.0.0"
}
} public void ConfigureServices(IServiceCollection services)
{
services.AddSession(); public void Configure(IApplicationBuilder app)
{
app.UseSession(); app.UseSession(options: new SessionOptions
{
IdleTimeout = TimeSpan.FromMinutes(30),
CookieName = ".MyApplication"
}); public ActionResult TestSession()
{
this.HttpContext.Session.Set("key-1", BitConverter.GetBytes(DateTime.Now.Ticks));
this.HttpContext.Session.SetInt32("key-2", 1);
this.HttpContext.Session.SetString("key-3", "DNT");
return Content("OK!");
} public IActionResult Index()
{
byte[] key1 = this.HttpContext.Session.Get("key-1");
long key1Value = BitConverter.ToInt64(key1, 0);
int? key2Value = this.HttpContext.Session.GetInt32("key-2");
string key3Value = this.HttpContext.Session.GetString("key-3");
return Content("OK!");
} using System;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
namespace Core1RtmEmptyTest.StartupCustomizations
{
public static class SessionExts
{
public static void SetDateTime(this ISession collection, string key, DateTime value)
{
collection.Set(key, BitConverter.GetBytes(value.Ticks));
}
public static DateTime? GetDateTime(this ISession collection, string key)
{
var data = collection.Get(key);
if (data == null)
{
return null;
}
var dateInt = BitConverter.ToInt64(data, 0);
return new DateTime(dateInt);
}
public static void SetObject(this ISession session, string key, object value)
{
var stringValue = JsonConvert.SerializeObject(value);
session.SetString(key, stringValue);
}
public static T GetObject<T>(this ISession session, string key)
{
var stringValue = session.GetString(key);
return JsonConvert.DeserializeObject<T>(stringValue);
}
}
} {
"dependencies": {
//same as before
"Microsoft.Extensions.Configuration.Json": "1.0.0"
}
} <Project Sdk="Microsoft.NET.Sdk.Web">
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Session" Version="1.1.1" />
</ItemGroup>
</Project> app.UseSession();
services.AddSession(options =>
{
options.Cookie.Name = ".mySite";
options.IdleTimeout = TimeSpan.FromMinutes(30);
}); 2017-10-30 14:46:15.846 +03:30 [Warning] Error unprotecting the session cookie. System.FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. at System.Convert.FromBase64_Decode(Char* startInputPtr, Int32 inputLength, Byte* startDestPtr, Int32 destLength) at System.Convert.FromBase64CharPtr(Char* inputPtr, Int32 inputLength) at System.Convert.FromBase64String(String s) at Microsoft.AspNetCore.Session.CookieProtection.Unprotect(IDataProtector protector, String protectedText, ILogger logger)
2017-10-30 14:46:16.169 +03:30 [Error] Error closing the session. System.OperationCanceledException: The operation was canceled. at System.Threading.CancellationToken.ThrowOperationCanceledException() at Microsoft.AspNetCore.Session.DistributedSession.<CommitAsync>d__32.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Session.SessionMiddleware.<Invoke>d__9.MoveNext()
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true; // consent required
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddSession(opts =>
{
opts.Cookie.IsEssential = true; // make the session cookie Essential
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
} public void ConfigureServices(ServiceCollection services)
{
services.AddSession(options =>
{
// Removed obsolete APIs
options.CookieName = "SessionCookie";
options.CookieDomain = "contoso.com";
options.CookiePath = "/";
options.CookieHttpOnly = true;
options.CookieSecure = CookieSecurePolicy.Always;
});
} public void ConfigureServices(ServiceCollection services)
{
services.AddSession(options =>
{
// new API
options.Cookie.Name = "SessionCookie";
options.Cookie.Domain = "contoso.com";
options.Cookie.Path = "/";
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});
}