|
| 1 | +using Microsoft.AspNetCore.Http; |
| 2 | +using System; |
| 3 | +using System.Collections.Generic; |
| 4 | +using System.Linq; |
| 5 | +using System.Threading.Tasks; |
| 6 | + |
| 7 | +namespace Ordering.API.Infrastructure.Middlewares |
| 8 | +{ |
| 9 | + public class FailingMiddleware |
| 10 | + { |
| 11 | + private readonly RequestDelegate _next; |
| 12 | + private bool _mustFail; |
| 13 | + private readonly FailingOptions _options; |
| 14 | + public FailingMiddleware(RequestDelegate next, FailingOptions options) |
| 15 | + { |
| 16 | + _next = next; |
| 17 | + _options = options; |
| 18 | + _mustFail = false; |
| 19 | + } |
| 20 | + public async Task Invoke(HttpContext context) |
| 21 | + { |
| 22 | + var path = context.Request.Path; |
| 23 | + if (path.Equals(_options.ConfigPath, StringComparison.OrdinalIgnoreCase)) |
| 24 | + { |
| 25 | + await ProcessConfigRequest(context); |
| 26 | + return; |
| 27 | + } |
| 28 | + |
| 29 | + |
| 30 | + if (_mustFail) |
| 31 | + { |
| 32 | + context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError; |
| 33 | + context.Response.ContentType = "text/plain"; |
| 34 | + await context.Response.WriteAsync("Failed due to FailingMiddleware enabled."); |
| 35 | + } |
| 36 | + else |
| 37 | + { |
| 38 | + await _next.Invoke(context); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + private async Task ProcessConfigRequest(HttpContext context) |
| 43 | + { |
| 44 | + int i = 0; |
| 45 | + var enable = context.Request.Query.Keys.Any(k => k == "enable"); |
| 46 | + var disable = context.Request.Query.Keys.Any(k => k == "disable"); |
| 47 | + |
| 48 | + if (enable && disable) |
| 49 | + { |
| 50 | + throw new ArgumentException("Must use enable or disable querystring values, but not both"); |
| 51 | + } |
| 52 | + |
| 53 | + if (disable) |
| 54 | + { |
| 55 | + _mustFail = false; |
| 56 | + await SendOkResponse(context, "FailingMiddleware disabled. Further requests will be processed."); |
| 57 | + return; |
| 58 | + } |
| 59 | + if (enable) |
| 60 | + { |
| 61 | + _mustFail = true; |
| 62 | + await SendOkResponse(context, "FailingMiddleware enabled. Further requests will return HTTP 500"); |
| 63 | + return; |
| 64 | + } |
| 65 | + |
| 66 | + // If reach here, that means that no valid parameter has been passed. Just output status |
| 67 | + await SendOkResponse(context, string.Format("FailingMiddleware is {0}", _mustFail ? "enabled" : "disabled")); |
| 68 | + return; |
| 69 | + } |
| 70 | + |
| 71 | + private async Task SendOkResponse(HttpContext context, string message) |
| 72 | + { |
| 73 | + context.Response.StatusCode = (int)System.Net.HttpStatusCode.OK; |
| 74 | + context.Response.ContentType = "text/plain"; |
| 75 | + await context.Response.WriteAsync(message); |
| 76 | + } |
| 77 | + |
| 78 | + } |
| 79 | +} |
0 commit comments