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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
using Microsoft.AspNetCore.Hosting; //IWebHostBuilder using Microsoft.AspNetCore.Builder; //IApplicationBuilder using Microsoft.AspNetCore.Http; //WriteAsync using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Rewrite; //UseRewriter using System; using System.Net; using Microsoft.Net.Http.Headers; using System.IO; namespace WebApplication1 { public class ExtensionRedirection : IRule { readonly string _extension; readonly PathString _newPath; public ExtensionRedirection(string extension, string newPath) { _extension = extension; _newPath = new PathString(newPath); } public void ApplyRule(RewriteContext context) { var request = context.HttpContext.Request; // Because we're redirecting back to the same app, stop processing if the request has already been redirected // This is to prevent crazy loop. Try it, comment below code and you are going to crash. if (request.Path.StartsWithSegments(new PathString(_newPath))) { return; } if (request.Path.Value.EndsWith(_extension, StringComparison.OrdinalIgnoreCase)) { var response = context.HttpContext.Response; response.StatusCode = StatusCodes.Status301MovedPermanently; context.Result = RuleResult.EndResponse; response.Headers[HeaderNames.Location] = _newPath + request.Path + request.QueryString; } } } public class Startup { public Startup(IHostingEnvironment env, ILoggerFactory logger) { } public void ConfigureServices(IServiceCollection services) { //This is the only service available at ConfigureServices services.AddRouting(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger) { var options = new RewriteOptions() .Add(new ExtensionRedirection(".png", "/images/png")) .Add(new ExtensionRedirection(".jpg", "/images/jpeg")); app.UseRewriter(options); app.UseStaticFiles(); var routes = new RouteBuilder(app); routes.MapGet("", async context => { context.Response.Headers.Add("content-type", "text/html"); var path = context.Request.Query["Path"]; var ext = context.Request.Query["Ext"]; await context.Response.WriteAsync($"<h1>Extension Based Redirection</h1><img src=\"ryan-wong-25025.jpg\" /> <br/> <img src=\"Acorn_PNG744.png\" />"); }); app.UseRouter(routes.Build()); } } public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseEnvironment("Development"); } } |
결과 :
Extension Based Redirection
[이미지] //생략
[이미지] //생략