Support IOptions<RewriteOptions> (#243)

- Added a test
- Updated the sample to use services
This commit is contained in:
David Fowler 2017-06-08 14:01:04 -10:00 коммит произвёл GitHub
Родитель 80ec97c132
Коммит 00343d2b47
4 изменённых файлов: 74 добавлений и 17 удалений

Просмотреть файл

@ -7,22 +7,39 @@ using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.Extensions.DependencyInjection;
namespace RewriteSample
{
public class Startup
{
public Startup(IHostingEnvironment environment)
{
Environment = environment;
}
public IHostingEnvironment Environment { get; private set; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<RewriteOptions>(options =>
{
options.AddRedirect("(.*)/$", "$1")
.AddRewrite(@"app/(\d+)", "app?id=$1", skipRemainingRules: false)
.AddRedirectToHttps(302, 5001)
.AddIISUrlRewrite(Environment.ContentRootFileProvider, "UrlRewrite.xml")
.AddApacheModRewrite(Environment.ContentRootFileProvider, "Rewrite.txt");
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var options = new RewriteOptions()
.AddRedirect("(.*)/$", "$1")
.AddRewrite(@"app/(\d+)", "app?id=$1", skipRemainingRules: false)
.AddRedirectToHttps(302, 5001)
.AddIISUrlRewrite(env.ContentRootFileProvider, "UrlRewrite.xml")
.AddApacheModRewrite(env.ContentRootFileProvider, "Rewrite.txt");
app.UseRewriter();
app.UseRewriter(options);
app.Run(context => context.Response.WriteAsync($"Rewritten Url: {context.Request.Path + context.Request.QueryString}"));
app.Run(context =>
{
return context.Response.WriteAsync($"Rewritten Url: {context.Request.Path + context.Request.QueryString}");
});
}
public static void Main(string[] args)

Просмотреть файл

@ -3,6 +3,7 @@
using System;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Builder
{
@ -11,6 +12,21 @@ namespace Microsoft.AspNetCore.Builder
/// </summary>
public static class RewriteBuilderExtensions
{
/// <summary>
/// Checks if a given Url matches rules and conditions, and modifies the HttpContext on match.
/// </summary>
/// <param name="app">The <see cref="IApplicationBuilder"/></param>
/// <returns></returns>
public static IApplicationBuilder UseRewriter(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
return app.UseMiddleware<RewriteMiddleware>();
}
/// <summary>
/// Checks if a given Url matches rules and conditions, and modifies the HttpContext on match.
/// </summary>
@ -28,8 +44,9 @@ namespace Microsoft.AspNetCore.Builder
{
throw new ArgumentNullException(nameof(options));
}
// put middleware in pipeline
return app.UseMiddleware<RewriteMiddleware>(options);
return app.UseMiddleware<RewriteMiddleware>(Options.Create(options));
}
}
}

Просмотреть файл

@ -6,11 +6,11 @@ using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Rewrite.Internal.IISUrlRewrite;
using Microsoft.AspNetCore.Rewrite.Logging;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Rewrite
@ -36,7 +36,7 @@ namespace Microsoft.AspNetCore.Rewrite
RequestDelegate next,
IHostingEnvironment hostingEnvironment,
ILoggerFactory loggerFactory,
RewriteOptions options)
IOptions<RewriteOptions> options)
{
if (next == null)
{
@ -49,7 +49,7 @@ namespace Microsoft.AspNetCore.Rewrite
}
_next = next;
_options = options;
_options = options.Value;
_fileProvider = _options.StaticFileProvider ?? hostingEnvironment.WebRootFileProvider;
_logger = loggerFactory.CreateLogger<RewriteMiddleware>();
}

Просмотреть файл

@ -7,6 +7,7 @@ using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Microsoft.AspNetCore.Rewrite.Tests.CodeRules
@ -38,7 +39,7 @@ namespace Microsoft.AspNetCore.Rewrite.Tests.CodeRules
[Fact]
public async Task CheckRedirectPath()
{
var options = new RewriteOptions().AddRedirect("(.*)","http://example.com/$1", statusCode: StatusCodes.Status301MovedPermanently);
var options = new RewriteOptions().AddRedirect("(.*)", "http://example.com/$1", statusCode: StatusCodes.Status301MovedPermanently);
var builder = new WebHostBuilder()
.Configure(app =>
{
@ -51,10 +52,32 @@ namespace Microsoft.AspNetCore.Rewrite.Tests.CodeRules
Assert.Equal("http://example.com/foo", response.Headers.Location.OriginalString);
}
[Fact]
public async Task RewriteRulesCanComeFromConfigureOptions()
{
var builder = new WebHostBuilder()
.ConfigureServices(services =>
{
services.Configure<RewriteOptions>(options =>
{
options.AddRedirect("(.*)", "http://example.com/$1", statusCode: StatusCodes.Status301MovedPermanently);
});
})
.Configure(app =>
{
app.UseRewriter();
});
var server = new TestServer(builder);
var response = await server.CreateClient().GetAsync("foo");
Assert.Equal("http://example.com/foo", response.Headers.Location.OriginalString);
}
[Fact]
public async Task CheckRedirectPathWithQueryString()
{
var options = new RewriteOptions().AddRedirect("(.*)","http://example.com/$1", statusCode: StatusCodes.Status301MovedPermanently);
var options = new RewriteOptions().AddRedirect("(.*)", "http://example.com/$1", statusCode: StatusCodes.Status301MovedPermanently);
var builder = new WebHostBuilder()
.Configure(app =>
{
@ -108,9 +131,9 @@ namespace Microsoft.AspNetCore.Rewrite.Tests.CodeRules
[Theory]
[InlineData(25, "https://example.com:25/")]
[InlineData(-25, "https://example.com/")]
public async Task CheckRedirectToHttpsWithSslPort(int sslPort,string expected)
public async Task CheckRedirectToHttpsWithSslPort(int sslPort, string expected)
{
var options = new RewriteOptions().AddRedirectToHttps(statusCode: StatusCodes.Status301MovedPermanently, sslPort:sslPort);
var options = new RewriteOptions().AddRedirectToHttps(statusCode: StatusCodes.Status301MovedPermanently, sslPort: sslPort);
var builder = new WebHostBuilder()
.Configure(app =>
{
@ -170,7 +193,7 @@ namespace Microsoft.AspNetCore.Rewrite.Tests.CodeRules
context.Request.Path +
context.Request.QueryString));
});
var server = new TestServer(builder) {BaseAddress = new Uri("http://localhost:5000/foo")};
var server = new TestServer(builder) { BaseAddress = new Uri("http://localhost:5000/foo") };
var response = await server.CreateClient().GetAsync("");