-
Notifications
You must be signed in to change notification settings - Fork 6
/
WebApiService.cs
94 lines (80 loc) · 2.68 KB
/
WebApiService.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
88
89
90
91
92
93
94
using System;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http;
using Microsoft.Owin.Hosting;
using Owin;
namespace WcfVsWebApiVsAspNetCoreBenchmark
{
public class WebApiService<T>: RestServiceBase<T>
where T: class, new()
{
public void Start()
{
var startup = new WebApiStartup<T>(_format);
_app = WebApp.Start($"http://localhost:{_port}", startup.Configuration);
InitializeClients();
}
public void Stop()
{
_app.Dispose();
}
public WebApiService(int port, SerializerType format, int itemCount)
: base(port, format, itemCount)
{
_port = port;
_format = format;
}
private readonly int _port;
private readonly SerializerType _format;
private IDisposable _app;
}
public class WebApiController: ApiController
{
[HttpPost, Route("api/operation/SmallItem")]
public SmallItem[] ItemOperation([FromBody] SmallItem[] items, int itemCount)
{
return Cache.SmallItems.Take(itemCount).ToArray();
}
[HttpPost, Route("api/operation/LargeItem")]
public LargeItem[] LargeItemOperation([FromBody] LargeItem[] items, int itemCount)
{
return Cache.LargeItems.Take(itemCount).ToArray();
}
}
public class WebApiStartup<T>
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Formatters.Clear();
switch(_format)
{
case SerializerType.Xml:
config.Formatters.Add(new XmlMediaTypeFormatter
{
UseXmlSerializer = true,
});
break;
case SerializerType.JsonNet:
config.Formatters.Add(new JsonMediaTypeFormatter());
break;
case SerializerType.MessagePack:
config.Formatters.Add(new MessagePackMediaTypeFormatter<T>());
break;
case SerializerType.Utf8Json:
config.Formatters.Add(new Utf8JsonMediaTypeFormatter<T>());
break;
default:
throw new ArgumentOutOfRangeException();
}
app.UseWebApi(config);
}
public WebApiStartup(SerializerType format)
{
_format = format;
}
private readonly SerializerType _format;
}
}