ln.http/HttpRequest.cs

122 lines
3.6 KiB
C#

using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using ln.http.exceptions;
namespace ln.http
{
public class HttpRequest
{
Dictionary<String, String> requestHeaders;
public IPEndPoint RemoteEndpoint { get; private set; }
public IPEndPoint LocalEndpoint { get; private set; }
public Uri BaseURI { get; set; }
public Uri URI { get; private set; }
public String Method { get; private set; }
public String RequestURL { get; private set; }
public String Protocol { get; private set; }
public String Hostname { get; private set; }
public int Port { get; private set; }
public QueryStringParameters Query { get; private set; }
public HttpRequest(HttpReader httpReader,IPEndPoint localEndpoint)
{
LocalEndpoint = localEndpoint;
RemoteEndpoint = httpReader.RemoteEndpoint;
Method = httpReader.Method;
Protocol = httpReader.Protocol;
RequestURL = httpReader.URL;
requestHeaders = new Dictionary<string, string>(httpReader.Headers);
Setup();
}
private void Setup()
{
SetupResourceURI();
}
/*
* SetupResourceURI()
*
* Setup the following fields:
*
* - Hostname
* - Port
* - BaseURI
* - URI
* - Query
*
*/
private void SetupResourceURI()
{
String host = GetRequestHeader("HOST");
String[] hostTokens = host.Split(':');
Hostname = hostTokens[0];
Port = (hostTokens.Length > 1) ? int.Parse(hostTokens[1]) : LocalEndpoint.Port;
BaseURI = new UriBuilder("http", Hostname, Port).Uri;
URI = new Uri(BaseURI, RequestURL);
Query = new QueryStringParameters(URI.Query);
}
public override string ToString()
{
//return string.Format("[HttpRequest: RemoteEndpoint={0}, Hostname={1} Port={2} URI={4}, Method={4}, RequestURL={5}, Protocol={6} Query={7}]", RemoteEndpoint, URI, Method, RequestURL, Protocol, Hostname, Port,Query);
return base.ToString();
}
public String GetRequestHeader(String name, String def = "")
{
name = name.ToUpper();
if (requestHeaders.ContainsKey(name))
return requestHeaders[name];
return def;
}
public HttpResponse Redirect(string location,int status = 301)
{
HttpResponse httpResponse = new HttpResponse(this);
httpResponse.AddHeader("location", location);
httpResponse.StatusCode = status;
httpResponse.AddHeader("content-type", "text/plain");
httpResponse.ContentWriter.WriteLine("Redirect: {0}", location);
return httpResponse;
}
//private void SendResponse()
//{
// using (StreamWriter writer = new StreamWriter(this.stream))
// {
// ResponseStream.Position = 0;
// SetResponseHeader("Content-Length", responseStream.Length.ToString());
// writer.WriteLine("{0} {1} {2}", Protocol, StatusCode, HttpStatusCodes.GetStatusMessage(StatusCode));
// foreach (String rhName in responseHeaders.Keys){
// writer.WriteLine("{0}: {1}", rhName, responseHeaders[rhName]);
// }
// writer.WriteLine();
// writer.Flush();
// responseStream.CopyTo(this.stream);
// }
//}
}
}