我将httplistener与基于以下代码的代码一起使用:
https://aksakalli.github.io/2014/02/24/simple-http-server-with-csparp.html
我正在尝试实施会话。
很遗憾,我在 HttpListenerContext 中找不到与该会话相关的任何内容。
我还尝试使用 System.Web.HttpContext.Current.Session.SessionID 但这给我带来了一个错误“对象引用未设置为对象的实例”
我将不胜感激。
示例代码:
private void ProcessContext(HttpListenerContext context)
{
// get filename path
string filename = context.Request.Url.AbsolutePath;
if (filename != null) filename = filename.Substring(1);
// get default index file if needed
if (string.IsNullOrEmpty(filename))
{
foreach (string indexFile in indexFiles)
{
if (File.Exists(Path.Combine(path, indexFile)))
{
filename = indexFile;
break;
}
}
}
Console.WriteLine("Loading file: " + filename);
filename = Path.Combine(path, filename);
// send file
HttpStatusCode statusCode;
if (File.Exists(filename))
{
try
{
using (var stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
// get mime type
context.Response.ContentType = mimeTypes[Path.GetExtension(filename)];
context.Response.ContentLength64 = stream.Length;
// copy file stream to response
stream.CopyTo(context.Response.OutputStream);
stream.Flush();
context.Response.OutputStream.Flush();
}
statusCode = HttpStatusCode.OK;
}
catch (Exception e)
{
Console.WriteLine("ERROR: " + e.Message);
statusCode = HttpStatusCode.InternalServerError;
}
}
else
{
Console.WriteLine("File not found: " + filename);
statusCode = HttpStatusCode.NotFound;
}
// finish
context.Response.StatusCode = (int)statusCode;
if (statusCode == HttpStatusCode.OK)
{
context.Response.AddHeader("Date", DateTime.Now.ToString("r"));
context.Response.AddHeader("Last-Modified", File.GetLastWriteTime(filename).ToString("r"));
}
context.Response.OutputStream.Close();
}