ich habe recht lange für eine eigentlich einfache Implementierung gebraucht und bin mir immer noch nicht wirklich im Klaren, ob das so richtig designt und gecodet ist.
Und zwar habe ich 3 Klassen. Die Uri-Klasse des .NET-Frameworks, eine HttpUrl-Klasse, die nur Http- und Https-Uris erlauben soll (und dementsprechend von Uri ableiten sollten) und die HttpServer-Klasse, die neben Eigenschaften wie Erreichbarkeit und eben der Http(s)-Uri auch noch die Möglichkeit des Vergleiches bieten soll. Beispielsweise soll "http://www.example.net" == "http://example.net/" sein. Ein weiterer Punkt soll sein, dass beim Erstellen eines HttpServers mit dem String "http://www.example.net/path" der HttpServer "http://www.example.net/" erstellt werden soll.
Gibt da wohl genug Wege, die nach Rom führen...
Genug erzählt, nun gibts Code:
public class HttpUrl : Uri
{
public static readonly Regex DomainRegex = new Regex(@"https?://(www\.)?(?<basedomain>[A-Za-z\d_.-]+\.[A-Za-z]{2,4})", RegexOptions.ExplicitCapture);// ~ ?
public string BaseDomain { get; private set; }// z.B.: "example.net"
public string Domain { get; private set; }// z.B.: http://www.example.net/
private HttpUrl(string httpUrlString)
:base(httpUrlString)
{
}
public static HttpUrl Create(string httpUrlString, bool removePathAndQueries = false)
{
Match match = VerifyDomainMatch(httpUrlString);
HttpUrl httpUrl;
string domain = AppendSlash(match.Value);
if (removePathAndQueries)
httpUrl = new HttpUrl(domain);
else
httpUrl = new HttpUrl(httpUrlString);
httpUrl.Domain = domain;
httpUrl.BaseDomain = match.Groups["basedomain"].Value;
return httpUrl;
}
private static string AppendSlash(string httpDomain)
{
return string.Concat(httpDomain, "/");// http://www.example.net --> http://www.example.net/
}
private static Match VerifyDomainMatch(string url)
{
Match match = DomainRegex.Match(url);
if (!match.Success)
throw new FormatException("Die angegebene URL ist nicht im korrekten Http-Url-Format.");
return match;
}
public class HttpServer : IEquatable<HttpServer>
{
public HttpUrl Url { get; private set; }
public HttpServer(string httpDomain)
{
Url = HttpUrl.Create(httpDomain, true);
}
#region Overrides
public override bool Equals(object obj)
{
if (!(obj is HttpServer))
return false;
return Equals((HttpServer)obj);
}
public bool Equals(HttpServer other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Equals(Url.BaseDomain, other.Url.BaseDomain);
}
public override int GetHashCode()
{
return Url.BaseDomain.GetHashCode();
}
public static bool operator ==(HttpServer left, HttpServer right)
{
if (Object.ReferenceEquals(left, right))
return true;
return left.Equals(right);
}
public static bool operator !=(HttpServer left, HttpServer right)
{
return !(left == right);
}
public override string ToString()
{
return Url.AbsoluteUri;
}
#endregion
}
Viele Grüße
BlackMatrix