-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractRestModule.cs
More file actions
76 lines (67 loc) · 2.24 KB
/
Copy pathAbstractRestModule.cs
File metadata and controls
76 lines (67 loc) · 2.24 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
66
67
68
69
70
71
72
73
74
75
76
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using Nancy.ModelBinding;
using Nancy.Responses.Negotiation;
using Nancy.RestModule.Exceptions;
using Nancy.RestModule.Models;
using Nancy.Validation;
namespace Nancy.RestModule
{
public abstract class AbstractRestModule : NancyModule
{
private const string APPLICATION_JSON = "application/json";
protected AbstractRestModule(string path)
: base(path)
{
}
protected virtual MediaRange DefaultMediaRange
{
get { return new MediaRange(APPLICATION_JSON); }
}
protected virtual MediaRange DefaultContentType
{
get { return APPLICATION_JSON; }
}
protected virtual TRequest DoBind<TRequest>()
{
try
{
return this.Bind<TRequest>();
}
catch (ModelBindingException ex)
{
string message = string.Join(
"\n",
ex.PropertyBindingExceptions.Select(
e => string.Format(CultureInfo.InvariantCulture, "{0} - {1}", e.PropertyName, e.Message)));
throw new ModelBindingFailedException(message, ex);
}
catch (TargetInvocationException ex)
{
throw new ModelBindingFailedException(ex.Message, ex);
}
catch (SerializationException ex)
{
throw new ModelBindingFailedException(ex.Message, ex);
}
}
protected virtual void DoValidate<TRequest>(TRequest model)
{
this.Validate(model);
if (!ModelValidationResult.IsValid)
{
throw new ApiValidationException(ModelValidationResult);
}
}
protected virtual Negotiator DoNegotiate(ResponseModel response)
{
return Negotiate
.WithModel(response.Model)
.WithStatusCode(response.StatusCode)
.WithAllowedMediaRange(response.AllowedMediaRange ?? DefaultMediaRange)
.WithContentType(response.AllowedContentType ?? DefaultContentType);
}
}
}