This repository was archived by the owner on Aug 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathBasicApiProblemException.cs
More file actions
executable file
·65 lines (56 loc) · 2.21 KB
/
Copy pathBasicApiProblemException.cs
File metadata and controls
executable file
·65 lines (56 loc) · 2.21 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
64
65
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace WebApiProblem
{
public class BasicApiProblemException : ApiProblemException<BasicApiProblem>
{
public BasicApiProblemException(HttpStatusCode statusCode, string title, string problemTypeUrl, string detail = null)
{
ApiProblem = new BasicApiProblem { Title = title, Detail = detail, ProblemTypeUrl = problemTypeUrl };
StatusCode = statusCode;
}
public override string Serialize(string contentType)
{
if (contentType == "application/json")
{
return SerializeToJson();
}
return SerializeToXml();
}
private string SerializeToJson()
{
var serializer = JsonSerializer.Create(new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
using(var writer = new StringWriter())
{
serializer.Serialize(writer, ApiProblem);
var serialized = writer.GetStringBuilder().ToString();
return serialized;
}
}
private string SerializeToXml()
{
var namespaces = new XmlSerializerNamespaces();
namespaces.Add(string.Empty, WebApiProblemNames.XmlNamespaceName);
var serializer = new XmlSerializer(typeof (BasicApiProblem));
var encoding = Encoding.UTF8;
using (var memStream = new MemoryStream())
using (TextWriter writer = new StreamWriter(memStream, encoding))
{
serializer.Serialize(writer, ApiProblem, namespaces);
var data = memStream.ToArray();
var serialized = RemoveBom(encoding.GetString(data), encoding);
return serialized;
}
}
private static string RemoveBom(string p, Encoding encoding)
{
var bomMark = encoding.GetString(encoding.GetPreamble());
if (p.StartsWith(bomMark))
p = p.Remove(0, bomMark.Length);
return p.Replace("\0", "");
}
}
}