在ASP.NET中维护稳定的用户会话的标准方法是什么,而不必担心IIS回收,断开连接的用户,重新打开浏览器等等。 我希望我们的用户无需登录,除非每月一次,无论发生什么!
如果我使用自己的登录控件(不是标准的asp.net登录控件)也一样重要吗?如果我理解正确,我想我需要手动创建身份验证票。
答案 0 :(得分:2)
您可以在用户的计算机上设置身份验证Cookie,并将其设置为在月末过期。然后,您的身份验证代码可以简单地检查是否存在cookie,并根据cookie的内容自动登录用户。
答案 1 :(得分:1)
我不知道是否有'标准'方式。这取决于您的申请。基本的变化是您将会话数据放入一些在循环中持续存在的形式。我有一个应用程序,我正在保存有关“旅行”的信息,我将其序列化为xml文件。这是我在这种情况下使用的代码。这可能是一个有用的凝视地点:
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using Cravens.Infrastructure.Logging;
namespace TruckTrackerWeb.Code
{
public class TripSessions
{
private const string _relativeSesionFile = "~/App_Data/TripSessions.txt";
private readonly string _sessionFile;
private readonly ILogger _logger;
private readonly Dictionary<Guid, TripSession> _sessions;
private readonly TimeSpan _maxAge = new TimeSpan(1, 0, 0, 0);
public TripSessions(ILogger logger, HttpContextBase httpContextBase)
{
_logger = logger;
_sessionFile = httpContextBase.Server.MapPath(_relativeSesionFile);
_sessions = ReadSessionFile();
}
public TripSession CreateSession(string userName, int truckId)
{
try
{
TripSession tripSession = new TripSession
{
Id = Guid.NewGuid(),
Expiration = DateTime.Now + _maxAge,
TruckId = truckId,
UserName = userName
};
_sessions[tripSession.Id] = tripSession;
SaveSessionFile();
_logger.Debug("Created session for: username=" + userName + ",truckid=" + truckId);
return tripSession;
}
catch (Exception ex)
{
_logger.Error("Failed to create session. ", ex);
}
return null;
}
public TripSession GetSession(Guid id)
{
if(_sessions.ContainsKey(id))
{
return _sessions[id];
}
return null;
}
private void SaveSessionFile()
{
_logger.Debug("Saving trip session data to file.");
List<string> lines = new List<string>();
foreach (KeyValuePair<Guid, TripSession> keyValuePair in _sessions)
{
TripSession tripSession = keyValuePair.Value;
lines.Add(tripSession.ToString());
}
File.WriteAllLines(_sessionFile, lines.ToArray());
}
private Dictionary<Guid, TripSession> ReadSessionFile()
{
_logger.Debug("******READING TRIP SESSION FILE**********");
Dictionary<Guid, TripSession> result = new Dictionary<Guid, TripSession>();
if(!File.Exists(_sessionFile))
{
_logger.Debug("The session file does not exist. file=" + _sessionFile);
return result;
}
string[] lines = File.ReadAllLines(_sessionFile);
foreach (string line in lines)
{
TripSession tripSession = TripSession.ParseLine(line);
if(tripSession!=null && (DateTime.Now - tripSession.Expiration)<_maxAge)
{
result[tripSession.Id] = tripSession;
_logger.Debug("ADDED---->" + line);
}
else
{
_logger.Debug("EXPIRED-->" + line);
}
}
return result;
}
}
}
答案 2 :(得分:1)
参加您的会话out of process
并将SessionTimeout
增加到最多