-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathHttpExtensions.cs
51 lines (44 loc) · 1.64 KB
/
HttpExtensions.cs
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
46
47
48
49
50
51
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Microsoft.AspNetCore.WebUtilities;
using System.Text;
namespace LightweightApiWithAuth
{
public static class HttpExtensions
{
private static readonly JsonSerializer Serializer = new JsonSerializer();
public static void WriteJson<T>(this HttpResponse response, T obj)
{
response.ContentType = "application/json";
using (var writer = new HttpResponseStreamWriter(response.Body, Encoding.UTF8))
{
using (var jsonWriter = new JsonTextWriter(writer))
{
jsonWriter.CloseOutput = false;
jsonWriter.AutoCompleteOnClose = false;
Serializer.Serialize(jsonWriter, obj);
}
}
}
public static T ReadFromJson<T>(this HttpContext httpContext)
{
using (var streamReader = new StreamReader(httpContext.Request.Body))
using (var jsonTextReader = new JsonTextReader(streamReader))
{
var obj = Serializer.Deserialize<T>(jsonTextReader);
var results = new List<ValidationResult>();
if (Validator.TryValidateObject(obj, new ValidationContext(obj), results))
{
return obj;
}
httpContext.Response.StatusCode = 400;
httpContext.Response.WriteJson(results);
return default(T);
}
}
}
}