-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathXmlValueProvider.cs
87 lines (77 loc) · 2.65 KB
/
XmlValueProvider.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Globalization;
using System.Web.Http.Controllers;
using System.Xml.Serialization;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
using System.Xml;
using System.Xml.Linq;
namespace MVCNet.Utils
{
public class XmlValueProvider: IValueProvider
{
private Dictionary<string, object> _values;
public XmlValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
_values = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
this.GetValuesFromRequest(controllerContext);
}
protected void GetValuesFromRequest(ControllerContext controllerContext)
{
if ((controllerContext.HttpContext.Request.ContentType ?? String.Empty).Contains("application/xml"))
{
using (StreamReader stream = new StreamReader(controllerContext.HttpContext.Request.InputStream))
{
string content = stream.ReadToEnd();
XDocument xmlInput = XDocument.Parse(content);
if(xmlInput != null)
{
XElement root = xmlInput.Root;
if(root != null && root.HasElements)
{
IEnumerable<XElement> elements = root.Elements();
foreach (var element in elements)
{
if (element.NodeType == XmlNodeType.Element)
{
if (!_values.Keys.Contains(element.Name.ToString()))
{
_values.Add(element.Name.ToString(), element.Value);
}
}
}
}
}
}
}
}
public bool ContainsPrefix(string prefix)
{
return _values.Keys.Contains(prefix.ToLower());
}
public ValueProviderResult GetValue(string key)
{
object value;
if (_values.TryGetValue(key.ToLower(), out value))
{
return new ValueProviderResult(value, value.ToString(), CultureInfo.InvariantCulture);
}
return null;
}
}
public class XmlValueProviderFactory : ValueProviderFactory
{
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
return new XmlValueProvider(controllerContext);
}
}
}