init commit

parents
bin/
obj/
/packages/
riderModule.iml
/_ReSharper.Caches/
\ No newline at end of file

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyHttpServer", "MyHttpServer\MyHttpServer.csproj", "{3FA916A1-E657-43B8-9E21-3BFB4C6DBB99}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{3FA916A1-E657-43B8-9E21-3BFB4C6DBB99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3FA916A1-E657-43B8-9E21-3BFB4C6DBB99}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3FA916A1-E657-43B8-9E21-3BFB4C6DBB99}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3FA916A1-E657-43B8-9E21-3BFB4C6DBB99}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
using RazorEngine;
using RazorEngine.Templating;
using Encoding = System.Text;
namespace MyHttpServer
{
public class MyHttpServer
{
private Thread _serverThread;
private string _siteDirectory;
private HttpListener _listener;
private int _port;
public MyHttpServer(string path, int port)
{
this.Initialize(path, port);
}
private void Initialize(string path, int port)
{
_siteDirectory = path;
_port = port;
_serverThread = new Thread(Listen);
_serverThread.Start();
Console.WriteLine($"Сервер запущен на порту: {port}");
Console.WriteLine($"Файлы сайта лежат в папке {path}");
}
private void Listen()
{
_listener = new HttpListener();
_listener.Prefixes.Add("http://localhost:" + _port.ToString() + "/");
_listener.Start();
while (true)
{
try
{
HttpListenerContext context = _listener.GetContext();
Process(context);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
break;
}
}
Stop();
}
private void Process(HttpListenerContext context)
{
string url = context.Request.Url.ToString();
string filename = context.Request.Url.AbsolutePath;
Console.WriteLine(filename);
filename = filename.Substring(1);
filename = Path.Combine(_siteDirectory, filename);
if (File.Exists(filename))
{
try
{
string content;
if (filename.Contains("html"))
{
content = BuildHtml(filename);
}
else
{
content = File.ReadAllText(filename);
}
byte[] htmlBytes = Encoding.Encoding.UTF8.GetBytes(content);
Stream fileStream = new MemoryStream(htmlBytes);
context.Response.ContentType = GetContentType(filename);
context.Response.ContentLength64 = fileStream.Length;
byte[] buffer = new byte[16 * 1024];
int dataLength;
do
{
dataLength = fileStream.Read(buffer, 0, buffer.Length);
context.Response.OutputStream.Write(buffer, 0, dataLength);
} while (dataLength > 0);
fileStream.Close();
context.Response.StatusCode = (int) HttpStatusCode.OK;
context.Response.OutputStream.Flush();
}
catch (Exception e)
{
Console.WriteLine(e);
context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
}
}
else
{
context.Response.StatusCode = (int) HttpStatusCode.NotFound;
}
context.Response.OutputStream.Close();
}
private string GetContentType(string filename)
{
var dictionary = new Dictionary<string, string>
{
{".css", "text/css"},
{".html", "text/html"},
{".ico", "image/x-icon"},
{".js", "application/x-javascript"},
{".json", "application/json"},
{".png", "image/png"}
};
string contentType = "";
string fileExension = Path.GetExtension(filename);
dictionary.TryGetValue(fileExension, out contentType);
return contentType;
}
public void Stop()
{
_serverThread.Abort();
_listener.Stop();
}
private string BuildHtml(string fileName)
{
string html = "";
string layoutPath = Path.Combine(_siteDirectory, "layout.html");
string filePath = Path.Combine(_siteDirectory, fileName);
var razorService = Engine.Razor;
if(!razorService.IsTemplateCached("layout", null))
razorService.AddTemplate("layout", File.ReadAllText(layoutPath));
if (!razorService.IsTemplateCached(fileName, null))
{
razorService.AddTemplate(fileName, File.ReadAllText(filePath));
razorService.Compile(fileName);
}
html = razorService.Run(fileName, null, new
{
IndexTitle = "Главная страница",
Page1 = "Страница 1",
Page2 = "Страница 2",
});
return html;
}
}
}
\ No newline at end of file
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Razor" Version="2.2.0" />
<PackageReference Include="RazorEngine.NetCore" Version="3.1.0" />
</ItemGroup>
<ItemGroup>
<None Update="site\style.css">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="site\page2.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="site\page!.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="site\layout.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="site\index.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
using System;
using System.IO;
using System.Text;
namespace MyHttpServer
{
class Program
{
static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
Console.InputEncoding = Encoding.UTF8;
string currentDir = Directory.GetCurrentDirectory();
string site = currentDir + @"\site";
MyHttpServer server = new MyHttpServer(site, 8888);
}
}
}
\ No newline at end of file
@{
Layout = "layout";
}
<h1>@Model.IndexTitle</h1>
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="topnav">
<a href="index.html">Главная страница</a>
<a href="page1.html">Страница 1</a>
<a href="page2.html">Страница 2</a>
</div>
@RenderBody();
</body>
</html>
\ No newline at end of file
@{
Layout = "layout";
}
<h1>@Model.Page1</h1>
\ No newline at end of file
@{
Layout = "layout";
}
<h1>@Model.Page2</h1>
h1 {
color: red
}
/* Add a black background color to the top navigation */
.topnav {
position: relative;
background-color: #333;
overflow: hidden;
}
/* Style the links inside the navigation bar */
.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
/* Change the color of links on hover */
.topnav a:hover {
background-color: #ddd;
color: black;
}
/* Add a color to the active/current link */
.topnav a.active {
background-color: #4CAF50;
color: white;
}
/* Centered section inside the top navigation */
.topnav-centered a {
float: none;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/* Right-aligned section inside the top navigation */
.topnav-right {
float: right;
}
/* Responsive navigation menu - display links on top of each other instead of next to each other (for mobile devices) */
@media screen and (max-width: 600px) {
.topnav a, .topnav-right {
float: none;
display: block;
}
.topnav-centered a {
position: relative;
top: 0;
left: 0;
transform: none;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment