-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathHttpResponseMessageExtensions.cs
More file actions
63 lines (59 loc) · 2.22 KB
/
HttpResponseMessageExtensions.cs
File metadata and controls
63 lines (59 loc) · 2.22 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using ViennaNET.Utils;
namespace ViennaNET.HttpClient
{
public static class HttpResponseMessageExtensions
{
private static readonly IEnumerable<MediaTypeFormatter> formatters = new List<MediaTypeFormatter>
{
new JsonMediaTypeFormatter(), new FormUrlEncodedMediaTypeFormatter()
};
private static string GetBadRequestMessage(string error)
{
try
{
var obj = JObject.Parse(error);
return (string)obj["Message"];
}
catch
{
return error;
}
}
/// <summary>
/// При успешном коде ответа, возвращает объект типа <see cref="ResultOf{T}" /> в состоянии 'Success'.
/// При ответе <see cref="HttpStatusCode.NotFound" /> возвращает <see cref="ResultOf{T}" /> в состоянии 'Empty'.
/// При ответе <see cref="HttpStatusCode.BadRequest" /> возвращает <see cref="ResultOf{T}" /> в состоянии 'Invalid'.
/// </summary>
/// <exception cref="InvalidOperationException">При неизвестных ответах</exception>
/// <typeparam name="T"></typeparam>
/// <param name="response"></param>
/// <returns>Объект типа <see cref="ResultOf{T}" />.</returns>
public static async Task<ResultOf<T>> HandleAsync<T>(this HttpResponseMessage response) where T : class
{
if (response.IsSuccessStatusCode)
{
var dto = await response.Content.ReadAsAsync<T>(formatters);
return ResultOf<T>.CreateSuccess(dto);
}
switch (response.StatusCode)
{
case HttpStatusCode.NotFound:
return ResultOf<T>.CreateEmpty();
case HttpStatusCode.BadRequest:
var error = await response.Content.ReadAsStringAsync();
var message = GetBadRequestMessage(error);
return ResultOf<T>.CreateInvalid(message);
default:
var exception = await response.Content.ReadAsStringAsync();
throw new InvalidOperationException(exception);
}
}
}
}