Skip to content

Commit 6b53067

Browse files
fix
1 parent f4d9e28 commit 6b53067

2 files changed

Lines changed: 18 additions & 6 deletions

File tree

MiniServer/HttpRequestArgs.cs

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
using System.Net;
22
using System.Text;
3+
using Microsoft.Extensions.Logging;
34
using Newtonsoft.Json;
45

56
namespace MiniServer;
67

7-
public class HttpRequestArgs(HttpListenerContext context)
8+
public class HttpRequestArgs(HttpListenerContext context, ILogger logger)
89
{
910
public HttpListenerContext Context { get; } = context;
1011
public string Path => Context.Request.RawUrl ?? string.Empty;
1112
public string Method => Context.Request.HttpMethod;
1213

14+
private readonly ILogger _logger = logger;
15+
1316
public void ReplyJson(object data, HttpStatusCode code)
1417
{
1518
string jsonResponse = JsonConvert.SerializeObject(data);
@@ -47,9 +50,18 @@ public void ReplyFile(byte[] buffer, HttpStatusCode code)
4750

4851
public void Reply(byte[] buffer, HttpStatusCode code, string contentType)
4952
{
50-
Context.Response.StatusCode = (int)code;
51-
Context.Response.ContentType = contentType;
52-
Context.Response.OutputStream.Write(buffer, 0, buffer.Length);
53-
Context.Response.Close();
53+
try
54+
{
55+
Context.Response.StatusCode = (int)code;
56+
Context.Response.ContentType = contentType;
57+
Context.Response.OutputStream.Write(buffer, 0, buffer.Length);
58+
Context.Response.Close();
59+
}
60+
catch (Exception ex)
61+
{
62+
_logger.LogError("Http Response Error: {ErrorMsg}", ex.Message);
63+
return;
64+
}
65+
5466
}
5567
}

MiniServer/Network/HttpServer.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ private async Task ReceiveLoopAsync(HttpListenerContext httpListenerContext, Can
7575
httpListenerContext.Response.Close();
7676
return;
7777
}
78-
var args = new HttpRequestArgs(httpListenerContext);
78+
var args = new HttpRequestArgs(httpListenerContext, _logger);
7979
try
8080
{
8181
_logger.LogInformation("[HttpReceive] 处理请求: {Path} {Method}", path, method);

0 commit comments

Comments
 (0)