|
1 | 1 | using System.Net; |
2 | 2 | using System.Text; |
| 3 | +using Microsoft.Extensions.Logging; |
3 | 4 | using Newtonsoft.Json; |
4 | 5 |
|
5 | 6 | namespace MiniServer; |
6 | 7 |
|
7 | | -public class HttpRequestArgs(HttpListenerContext context) |
| 8 | +public class HttpRequestArgs(HttpListenerContext context, ILogger logger) |
8 | 9 | { |
9 | 10 | public HttpListenerContext Context { get; } = context; |
10 | 11 | public string Path => Context.Request.RawUrl ?? string.Empty; |
11 | 12 | public string Method => Context.Request.HttpMethod; |
12 | 13 |
|
| 14 | + private readonly ILogger _logger = logger; |
| 15 | + |
13 | 16 | public void ReplyJson(object data, HttpStatusCode code) |
14 | 17 | { |
15 | 18 | string jsonResponse = JsonConvert.SerializeObject(data); |
@@ -47,9 +50,18 @@ public void ReplyFile(byte[] buffer, HttpStatusCode code) |
47 | 50 |
|
48 | 51 | public void Reply(byte[] buffer, HttpStatusCode code, string contentType) |
49 | 52 | { |
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 | + |
54 | 66 | } |
55 | 67 | } |
0 commit comments