-
-
Save NDiiong/e4f21ae4eb923c666a9fdc517daaa911 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.Extensions.Options; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace WebApp | |
{ | |
public class ShowAllServicesMiddleware | |
{ | |
private readonly ShowAllServicesConfig _config; | |
private readonly RequestDelegate _next; | |
public ShowAllServicesMiddleware(RequestDelegate next, | |
IOptions<ShowAllServicesConfig> config) | |
{ | |
_config = config.Value; | |
_next = next; | |
} | |
public async Task Invoke(HttpContext httpContext) | |
{ | |
if (httpContext.Request.Path.Equals(_config.Path)) | |
{ | |
var sb = new StringBuilder(); | |
sb.Append("<h1>All Services</h1>"); | |
sb.Append("<table><thead>"); | |
sb.Append("<tr><th>Type</th><th>Lifetime</th><th>Instance</th></tr>"); | |
sb.Append("</thead><tbody>"); | |
foreach (var serviceDescriptor in httpContext.RequestServices.GetService<IServiceCollection>()) | |
{ | |
sb.Append("<tr>"); | |
sb.Append($"<td>{serviceDescriptor.ServiceType.Name}</td>"); | |
sb.Append($"<td>{serviceDescriptor.Lifetime}</td>"); | |
sb.Append($"<td>{serviceDescriptor.ImplementationType?.Name}</td>"); | |
sb.Append("</tr>"); | |
} | |
sb.Append("</tbody></table>"); | |
await httpContext.Response.WriteAsync(sb.ToString()); | |
} | |
else | |
{ | |
await _next(httpContext); | |
} | |
} | |
} | |
// Extension method used to add the middleware to the HTTP request pipeline. | |
public static class ShowAllServicesMiddlewareExtensions | |
{ | |
public static IApplicationBuilder UseShowAllServicesMiddleware(this IApplicationBuilder builder) | |
{ | |
return builder.UseMiddleware<ShowAllServicesMiddleware>(); | |
} | |
} | |
public class ShowAllServicesConfig | |
{ | |
public string Path { get; set; } = "/appservices"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment