fixes for ServeFilesRouteHandler

This commit is contained in:
Timerix 2025-03-23 01:20:25 +05:00
parent 386d71260c
commit 2b5d6b6a54
3 changed files with 22 additions and 15 deletions

View File

@ -2,7 +2,7 @@
<PropertyGroup>
<!--package info-->
<PackageId>DTLib.Web</PackageId>
<Version>1.1.1</Version>
<Version>1.1.2</Version>
<Authors>Timerix</Authors>
<Description>HTTP Server with simple routing</Description>
<RepositoryType>GIT</RepositoryType>
@ -25,6 +25,6 @@
<ProjectReference Include="..\DTLib\DTLib.csproj" />
</ItemGroup>
<ItemGroup Condition=" '$(Configuration)' != 'Debug' ">
<PackageReference Include="DTLib" Version="1.6.4" />
<PackageReference Include="DTLib" Version="1.6.5" />
</ItemGroup>
</Project>

View File

@ -7,23 +7,30 @@ public class ServeFilesRouteHandler(IOPath _publicDir, string _homePageUrl = "in
if (ctx.Request.HttpMethod != "GET")
return HttpStatusCode.BadRequest;
string requestPath = ctx.Request.Url?.AbsolutePath ?? "/";
if (requestPath == "/")
string requestPath = ctx.Request.Url?.AbsolutePath!;
if (string.IsNullOrEmpty(requestPath) || requestPath == "/")
{
requestPath = _homePageUrl;
}
string ext = Path.Extension(requestPath).Str;
IOPath filePath = Path.Concat(_publicDir, requestPath);
if (!File.Exists(filePath))
return HttpStatusCode.NotFound;
string contentType = ext switch
List<(string key, string val)> headers = ext switch
{
"html" => "text/html",
"css" => "text/css",
"js" or "jsx" or "ts" or "tsx" or "map" => "text/javascript",
_ => "binary/octet-stream"
"html" => [("Content-Type", "text/html")],
"css" => [("Content-Type", "text/css")],
"js" or "jsx" or "ts" or "tsx" or "map" => [("Content-Type", "text/javascript")],
_ =>
[
("Content-Type", "binary/octet-stream"),
("Content-Disposition", $"attachment filename={filePath.LastName()}")
]
};
ctx.Response.Headers.Set("Content-Type", contentType);
ctx.Response.Headers.Set("Content-Disposition", "attachment filename=" + filePath.LastName());
foreach (var header in headers)
ctx.Response.Headers.Set(header.key, header.val);
var fileStream = File.OpenRead(filePath);
ctx.Response.ContentLength64 = fileStream.Length;

View File

@ -54,7 +54,7 @@ public class WebApp
{
_logger.LogInfo(logContext, $"[{ctx.Request.HttpMethod}] {ctx.Request.RawUrl} from {ctx.Request.RemoteEndPoint} ...");
var status = await _router.Resolve(ctx);
_logger.LogInfo(logContext, status);
_logger.LogInfo(logContext, $"{(int)status} ({status})");
}
catch (Exception ex)
{