Created
April 28, 2018 16:16
-
-
Save perokvist/d568749cbaca53bd36ca147a6799742a to your computer and use it in GitHub Desktop.
Robots Middleware
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
public class RobotsMiddleware | |
{ | |
private readonly RequestDelegate _next; | |
private readonly ILogger _logger; | |
public RobotsMiddleware(RequestDelegate next, ILoggerFactory loggerFactory) | |
{ | |
_next = next; | |
_logger = loggerFactory.CreateLogger<RobotsMiddleware>(); | |
} | |
public Task Invoke(HttpContext context) | |
=> Robots(context, () => _next(context), _logger); | |
private static Task Robots(HttpContext context, Func<Task> func, ILogger logger) | |
{ | |
if (context.Request.Path.ToString().ToLower() != "/robots.txt") | |
return func(); | |
var sb = new StringBuilder(); | |
sb.AppendLine("User-agent: *"); | |
sb.AppendLine("Disallow: /"); | |
context.Response.StatusCode = 200; | |
context.Response.ContentType = "text/plain"; | |
var content = sb.ToString(); | |
logger.LogDebug($"Serving robots.txt {content}"); | |
return context.Response.WriteAsync(content); | |
} | |
} | |
public static class RobotsExtensions | |
{ | |
public static IApplicationBuilder UseRobotsDontIndex(this IApplicationBuilder builder) | |
=> builder.UseMiddleware<RobotsMiddleware>(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment