-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathRoutingMiddleware.cs
51 lines (42 loc) · 2.1 KB
/
RoutingMiddleware.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
using System.Net;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
namespace AspNetCoreFromScratch;
public class RoutingMiddleware : IMiddleware
{
private readonly RouteRegistry _routeRegistry;
private readonly IServiceProvider _serviceProvider;
public RoutingMiddleware(RouteRegistry routeRegistry, IServiceProvider serviceProvider)
{
_routeRegistry = routeRegistry;
_serviceProvider = serviceProvider;
}
public async Task InvokeAsync(HttpListenerContext context, Func<Task> next)
{
Console.WriteLine("Inside RoutingMiddleware");
if (_routeRegistry.Routes.TryGetValue(context.Request.RawUrl[1..], out var controllerAction))
{
// Read the request body and deserialize it to the appropriate type.
using var reader = new StreamReader(context.Request.InputStream);
var requestBody = await reader.ReadToEndAsync();
// The type of object to deserialize to is determined by the method's first parameter.
var parameterType = controllerAction.Method.GetParameters()[0].ParameterType;
var requestObj = JsonSerializer.Deserialize(requestBody, parameterType);
// Fetch the controller from the DI container.
var controllerInstance = _serviceProvider.GetRequiredService(controllerAction.Controller);
// Invoke the controller method and get the result.
var actionResult = controllerAction.Method.Invoke(controllerInstance, new[] { requestObj });
// The type of object to serialize is determined by the method's return type.
var resultJson = JsonSerializer.Serialize(actionResult);
// Write the serialized result back to the response stream.
await context.Response.OutputStream.WriteAsync(Encoding.UTF8.GetBytes(resultJson));
}
else
{
// Short-circuit the pipeline, handle not found.
context.Response.StatusCode = 404;
await context.Response.OutputStream.WriteAsync("Not Found"u8.ToArray());
}
}
}