-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathHttpResponse.cs
More file actions
45 lines (38 loc) · 1.45 KB
/
HttpResponse.cs
File metadata and controls
45 lines (38 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
using System;
using System.Threading.Tasks;
using WeihanLi.Extensions;
namespace MiniAspNetCore
{
public class HttpResponse
{
private readonly IResponseFeature _responseFeature;
public HttpResponse(IFeatureCollection featureCollection)
{
_responseFeature = featureCollection.Get<IResponseFeature>();
}
public bool ResponseStarted => _responseFeature.Body.Length > 0;
public int StatusCode
{
get => _responseFeature.StatusCode;
set => _responseFeature.StatusCode = value;
}
public async Task WriteBytesAsync(byte[] responseBytes)
{
if (_responseFeature.StatusCode <= 0)
{
_responseFeature.StatusCode = 200;
}
if (responseBytes != null && responseBytes.Length > 0)
{
await _responseFeature.Body.WriteAsync(responseBytes);
}
}
}
public static class HttpResponseExtensions
{
public static Task WriteAsync(this HttpResponse response, string responseText)
=> string.IsNullOrEmpty(responseText) ? Task.CompletedTask : response.WriteBytesAsync(responseText.GetBytes());
public static Task WriteLineAsync(this HttpResponse response, string responseText)
=> string.IsNullOrEmpty(responseText) ? Task.CompletedTask : response.WriteBytesAsync($"{responseText}{Environment.NewLine}".GetBytes());
}
}