ContentType类型参考 https://www.runoob.com/http/http-content-type.html
作者:ludewig 链接:https://blog.csdn.net/lordwish/article/details/86615077
只是实现了Get的部分资源访问,用于展示简单的网页,解决JS需要IIS的跨域问题,在不需要搭建IIS的情况下显示内容
C#代码
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
namespace TestHttpListener
{
class Program
{
/// <summary>
/// 网页项目地址,最后需要加"\"
/// </summary>
static string path = @"网页项目地址";
/// <summary>
/// URL
/// </summary>
static string url = "http://localhost:8899/";
static void Main(string[] args)
{
HttpListener listener = new HttpListener();
listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
listener.Prefixes.Add(url);
listener.Start();
listener.BeginGetContext(ListenerHandle, listener);
Console.ReadKey();
listener.Stop();
listener.Close();
}
private static void ListenerHandle(IAsyncResult result)
{
HttpListener listener = result.AsyncState as HttpListener;
if (listener == null)
{
return;
}
if (listener.IsListening)
{
HttpListenerContext context = listener.EndGetContext(result);
listener.BeginGetContext(ListenerHandle, result.AsyncState);
//解析Request请求
HttpListenerRequest request = context.Request;
switch (request.HttpMethod)
{
case "POST":
break;
case "GET":
string filePath = string.Empty;
if (request.RawUrl=="/")
{
/*主页*/
filePath = Path.Combine(path, "index.html");
}
else
{
filePath = Path.Combine(path, request.RawUrl.Replace('/', '\\').TrimStart('\\'));
}
using (HttpListenerResponse response = context.Response)
{
response.ContentEncoding = Encoding.UTF8;
byte[] bytes = null;
if (File.Exists(filePath))
{
response.StatusCode = 200;
string suffixName = new FileInfo(filePath).Extension;
response.ContentType = $"{GetContentType(suffixName)};charset=UTF-8";
bytes = File.ReadAllBytes(filePath);
}
else
{
response.StatusCode = 200;
response.ContentType = "text/html;charset=UTF-8";
bytes = Encoding.UTF8.GetBytes("404");
}
using (Stream stream = response.OutputStream)
{
stream.Write(bytes, 0, bytes.Length);
}
}
break;
}
}
}
/// <summary>
/// 获取内容类型
/// 参考:https://www.runoob.com/http/http-content-type.html
/// </summary>
/// <param name="suffixName">文件后缀名称</param>
/// <returns>内容类型</returns>
private static string GetContentType(string suffixName)
{
string name = suffixName.ToLower();
switch (name)
{
case ".html":
return "text/html";
case ".jpeg":
case ".jpg":
return "image/jpeg";
case ".js":
return "application/x-javascript";
case ".css":
return "text/css";
case ".ico":
return "image/x-icon";
case ".json":
return "application/json";
default:
break;
}
return "text/plain";
}
}
}