/
FarticusMiddleware.cs
72 lines (62 loc) · 2.38 KB
/
FarticusMiddleware.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
using System;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.Framework.Logging;
using Microsoft.Framework.OptionsModel;
namespace Farticus
{
public class FarticusMiddleware
{
// This shouldn't be static as this middleware is constructed per pipeline lifetime.
private readonly ILogger _logger;
private readonly FarticusOptions _options;
// Get ILoggerFactory injected into this middleware as it was put inside the DI system
// by Microsoft.AspNet.Hosting at early points during the bootstrapping process.
public FarticusMiddleware(RequestDelegate next,
ILoggerFactory loggerFactory,
IOptions<FarticusOptions> options)
{
if(loggerFactory == null)
{
throw new ArgumentNullException("loggerFactory");
}
if(options == null)
{
throw new ArgumentNullException("options");
}
_logger = loggerFactory.Create(typeof(FarticusMiddleware).FullName);
_options = options.Options;
_logger.Write(
LogLevel.Information,
0,
"FarticusMiddleware has been successfully constructed.", null,
(state, ex) => (string)state);
}
public async Task Invoke(HttpContext context)
{
_logger.Write(
LogLevel.Verbose,
0,
"Processing the request.", null,
(state, ex) => (string)state);
IFarticusRepository repository = context
.RequestServices
.GetService(typeof(IFarticusRepository)) as IFarticusRepository;
if(repository == null)
{
throw new InvalidOperationException("IFarticusRepository is not available.");
}
var builder = new StringBuilder();
builder.Append("<div><strong>Farting...</strong></div>");
for(int i = 0; i < _options.NumberOfMessages; i++)
{
string message = await repository.GetFartMessageAsync();
builder.AppendFormat("<div>{0}</div>", message);
}
context.Response.ContentType = "text/html";
await context.Response.WriteAsync(builder.ToString());
}
}
}