using System;
using System.Web;
namespace OSHttpServer
{
///
/// cookie being sent back to the browser.
///
///
public class ResponseCookie : RequestCookie
{
private const string _nullPath = "/";
private bool _persistant = false;
private DateTime _expires;
private string _path = "/";
private readonly string _domain;
#region constructors
///
/// Constructor.
///
/// cookie identifier
/// cookie content
/// cookie expiration date. Use DateTime.MinValue for session cookie.
/// id or content is null
/// id is empty
public ResponseCookie(string id, string content, DateTime expiresAt)
: base(id, content)
{
if (expiresAt != DateTime.MinValue)
{
_expires = expiresAt;
_persistant = true;
}
}
///
/// Create a new cookie
///
/// name identifying the cookie
/// cookie value
/// when the cookie expires. Setting DateTime.MinValue will delete the cookie when the session is closed.
/// Path to where the cookie is valid
/// Domain that the cookie is valid for.
public ResponseCookie(string name, string value, DateTime expires, string path, string domain)
: this(name, value, expires)
{
_domain = domain;
_path = path;
}
///
/// Create a new cookie
///
/// Name and value will be used
/// when the cookie expires.
public ResponseCookie(RequestCookie cookie, DateTime expires)
: this(cookie.Name, cookie.Value, expires)
{}
#endregion
#region inherited methods
///
/// Gets the cookie HTML representation.
///
/// cookie string
public override string ToString()
{
string temp = string.Format("{0}={1}; ", HttpUtility.UrlEncode(Name), HttpUtility.UrlEncode(Value));
if (_persistant)
{
TimeSpan span = DateTime.Now - DateTime.UtcNow;
DateTime utc = _expires.Subtract(span);
temp += string.Format("expires={0};", utc.ToString("r"));
}
if (!string.IsNullOrEmpty(_path))
temp += string.Format("path={0}; ", _path);
if (!string.IsNullOrEmpty(_domain))
temp += string.Format("domain={0}; ", _domain);
return temp;
}
#endregion
#region public properties
///
/// When the cookie expires.
/// DateTime.MinValue means that the cookie expires when the session do so.
///
public DateTime Expires
{
get { return _expires; }
set
{
_expires = value;
_persistant = value != DateTime.MinValue;
}
}
///
/// Cookie is only valid under this path.
///
public string Path
{
get { return _path; }
set
{
if (!string.IsNullOrEmpty(value))
_path = value;
else
_path = _nullPath;
}
}
#endregion
}
}