-
-
Notifications
You must be signed in to change notification settings - Fork 209
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add WireMock.Net.AspNetCore.Middleware (#1175)
* Add WireMock.Net.AspNetCore.Middleware * . * WireMock.Net.Middleware.Tests * . * X-WireMock-Response-Delay
- Loading branch information
Showing
23 changed files
with
641 additions
and
1 deletion.
There are no files selected for viewing
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
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
using WireMock.Net.AspNetCore.Middleware; | ||
using WireMock.RequestBuilders; | ||
using WireMock.ResponseBuilders; | ||
|
||
var builder = WebApplication.CreateBuilder(args); | ||
|
||
if (!builder.Environment.IsProduction()) | ||
{ | ||
builder.Services.AddWireMockService(server => | ||
{ | ||
server.Given(Request.Create() | ||
.WithPath("/test1") | ||
.UsingAnyMethod() | ||
).RespondWith(Response.Create() | ||
.WithBody("1 : WireMock.Net !") | ||
); | ||
server.Given(Request.Create() | ||
.WithPath("/test2") | ||
.UsingAnyMethod() | ||
).RespondWith(Response.Create() | ||
.WithBody("2 : WireMock.Net !") | ||
); | ||
}, true); | ||
} | ||
|
||
var app = builder.Build(); | ||
|
||
app.MapGet("/weatherforecast", async (HttpClient client) => | ||
{ | ||
var result = await client.GetStringAsync("https://real-api:12345/test1"); | ||
return Enumerable.Range(1, 3).Select(index => | ||
new WeatherForecast | ||
( | ||
DateOnly.FromDateTime(DateTime.Now.AddDays(index)), | ||
Random.Shared.Next(-20, 55), | ||
result | ||
)); | ||
}); | ||
|
||
app.MapGet("/weatherforecast2", async (IHttpClientFactory factory) => | ||
{ | ||
using var client = factory.CreateClient(); | ||
var result = await client.GetStringAsync("https://real-api:12345/test2"); | ||
return Enumerable.Range(1, 3).Select(index => | ||
new WeatherForecast | ||
( | ||
DateOnly.FromDateTime(DateTime.Now.AddDays(index)), | ||
Random.Shared.Next(-20, 55), | ||
result | ||
)); | ||
}); | ||
|
||
await app.RunAsync(); |
41 changes: 41 additions & 0 deletions
41
examples/WireMock.Net.WebApplication/Properties/launchSettings.json
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
{ | ||
"$schema": "http://json.schemastore.org/launchsettings.json", | ||
"iisSettings": { | ||
"windowsAuthentication": false, | ||
"anonymousAuthentication": true, | ||
"iisExpress": { | ||
"applicationUrl": "http://localhost:57375", | ||
"sslPort": 44333 | ||
} | ||
}, | ||
"profiles": { | ||
"http": { | ||
"commandName": "Project", | ||
"dotnetRunMessages": true, | ||
"launchBrowser": true, | ||
"launchUrl": "weatherforecast", | ||
"applicationUrl": "http://localhost:5112", | ||
"environmentVariables": { | ||
"ASPNETCORE_ENVIRONMENT": "Development" | ||
} | ||
}, | ||
"https": { | ||
"commandName": "Project", | ||
"dotnetRunMessages": true, | ||
"launchBrowser": true, | ||
"launchUrl": "weatherforecast", | ||
"applicationUrl": "https://localhost:7021;http://localhost:5112", | ||
"environmentVariables": { | ||
"ASPNETCORE_ENVIRONMENT": "Development" | ||
} | ||
}, | ||
"IIS Express": { | ||
"commandName": "IISExpress", | ||
"launchBrowser": true, | ||
"launchUrl": "weatherforecast", | ||
"environmentVariables": { | ||
"ASPNETCORE_ENVIRONMENT": "Development" | ||
} | ||
} | ||
} | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary) | ||
{ | ||
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); | ||
} |
13 changes: 13 additions & 0 deletions
13
examples/WireMock.Net.WebApplication/WireMock.Net.WebApplication.csproj
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
<Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>net8.0</TargetFramework> | ||
<Nullable>enable</Nullable> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<ProjectReference Include="..\..\src\WireMock.Net.AspNetCore.Middleware\WireMock.Net.AspNetCore.Middleware.csproj" /> | ||
</ItemGroup> | ||
|
||
</Project> |
8 changes: 8 additions & 0 deletions
8
examples/WireMock.Net.WebApplication/appsettings.Development.json
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
{ | ||
"Logging": { | ||
"LogLevel": { | ||
"Default": "Debug", | ||
"Microsoft.AspNetCore": "Warning" | ||
} | ||
} | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
{ | ||
"Logging": { | ||
"LogLevel": { | ||
"Default": "Debug", | ||
"Microsoft.AspNetCore": "Warning" | ||
} | ||
}, | ||
"AllowedHosts": "*" | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
// Copyright © WireMock.Net | ||
|
||
namespace WireMock.Net.AspNetCore.Middleware; | ||
|
||
internal static class AppConstants | ||
{ | ||
internal const string HEADER_REDIRECT = "X-WireMock-Redirect"; | ||
internal const string HEADER_RESPONSE_DELAY = "X-WireMock-Response-Delay"; | ||
} |
72 changes: 72 additions & 0 deletions
72
src/WireMock.Net.AspNetCore.Middleware/HttpDelegatingHandler/WireMockDelegationHandler.cs
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,72 @@ | ||
using Microsoft.AspNetCore.Http; | ||
using Microsoft.Extensions.Logging; | ||
using Stef.Validation; | ||
using WireMock.Server; | ||
|
||
namespace WireMock.Net.AspNetCore.Middleware.HttpDelegatingHandler; | ||
|
||
/// <summary> | ||
/// DelegatingHandler that takes requests made via the <see cref="HttpClient"/> | ||
/// and routes them to the <see cref="WireMockServer"/>. | ||
/// </summary> | ||
internal class WireMockDelegationHandler : DelegatingHandler | ||
{ | ||
private readonly ILogger<WireMockDelegationHandler> _logger; | ||
private readonly WireMockServerInstance _server; | ||
private readonly IHttpContextAccessor _httpContextAccessor; | ||
private readonly WireMockDelegationHandlerSettings _settings; | ||
|
||
/// <summary> | ||
/// Creates a new instance of <see cref="WireMockDelegationHandler"/> | ||
/// </summary> | ||
public WireMockDelegationHandler( | ||
ILogger<WireMockDelegationHandler> logger, | ||
WireMockServerInstance server, | ||
IHttpContextAccessor httpContextAccessor, | ||
WireMockDelegationHandlerSettings settings | ||
) | ||
{ | ||
_server = Guard.NotNull(server); | ||
_httpContextAccessor = Guard.NotNull(httpContextAccessor); | ||
_logger = Guard.NotNull(logger); | ||
_settings = Guard.NotNull(settings); | ||
} | ||
|
||
/// <inheritdoc /> | ||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) | ||
{ | ||
Guard.NotNull(request); | ||
Guard.NotNull(_httpContextAccessor.HttpContext); | ||
|
||
if (_settings.AlwaysRedirect || IsWireMockRedirectHeaderSetToTrue()) | ||
{ | ||
_logger.LogDebug("Redirecting request to WireMock server"); | ||
if (_server.Instance?.Url != null) | ||
{ | ||
request.RequestUri = new Uri(_server.Instance.Url + request.RequestUri!.PathAndQuery); | ||
} | ||
} | ||
|
||
if (TryGetDelayHeaderValue(out var delayInMs)) | ||
{ | ||
await Task.Delay(delayInMs, cancellationToken); | ||
} | ||
|
||
return await base.SendAsync(request, cancellationToken); | ||
} | ||
|
||
private bool IsWireMockRedirectHeaderSetToTrue() | ||
{ | ||
return | ||
_httpContextAccessor.HttpContext!.Request.Headers.TryGetValue(AppConstants.HEADER_REDIRECT, out var values) && | ||
bool.TryParse(values.ToString(), out var shouldRedirectToWireMock) && shouldRedirectToWireMock; | ||
} | ||
|
||
private bool TryGetDelayHeaderValue(out int delayInMs) | ||
{ | ||
delayInMs = 0; | ||
return | ||
_httpContextAccessor.HttpContext!.Request.Headers.TryGetValue(AppConstants.HEADER_RESPONSE_DELAY, out var values) && | ||
int.TryParse(values.ToString(), out delayInMs); | ||
} | ||
} |
8 changes: 8 additions & 0 deletions
8
...Mock.Net.AspNetCore.Middleware/HttpDelegatingHandler/WireMockDelegationHandlerSettings.cs
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
// Copyright © WireMock.Net | ||
|
||
namespace WireMock.Net.AspNetCore.Middleware.HttpDelegatingHandler; | ||
|
||
internal class WireMockDelegationHandlerSettings | ||
{ | ||
public bool AlwaysRedirect { get; set; } | ||
} |
52 changes: 52 additions & 0 deletions
52
src/WireMock.Net.AspNetCore.Middleware/ServiceCollectionExtensions.cs
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
// Copyright © WireMock.Net | ||
|
||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.Http; | ||
using Stef.Validation; | ||
using WireMock.Net.AspNetCore.Middleware.HttpDelegatingHandler; | ||
using WireMock.Server; | ||
using WireMock.Settings; | ||
|
||
namespace WireMock.Net.AspNetCore.Middleware; | ||
|
||
/// <summary> | ||
/// Extension methods for <see cref="IServiceCollection"/>. | ||
/// </summary> | ||
public static class ServiceCollectionExtensions | ||
{ | ||
/// <summary> | ||
/// Adds all the components necessary to run WireMock.Net as a background service. | ||
/// </summary> | ||
public static IServiceCollection AddWireMockService( | ||
this IServiceCollection services, | ||
Action<WireMockServer> configure, | ||
bool alwaysRedirectToWireMock = true, | ||
WireMockServerSettings? settings = null | ||
) | ||
{ | ||
Guard.NotNull(services); | ||
Guard.NotNull(configure); | ||
|
||
services.AddTransient<WireMockDelegationHandler>(); | ||
|
||
services.AddSingleton(new WireMockServerInstance(configure, settings)); | ||
|
||
services.AddSingleton(new WireMockDelegationHandlerSettings | ||
{ | ||
AlwaysRedirect = alwaysRedirectToWireMock | ||
}); | ||
|
||
services.AddHostedService<WireMockBackgroundService>(); | ||
services.AddHttpClient(); | ||
services.AddHttpContextAccessor(); | ||
services.ConfigureAll<HttpClientFactoryOptions>(options => | ||
{ | ||
options.HttpMessageHandlerBuilderActions.Add(builder => | ||
{ | ||
builder.AdditionalHandlers.Add(builder.Services.GetRequiredService<WireMockDelegationHandler>()); | ||
}); | ||
}); | ||
|
||
return services; | ||
} | ||
} |
Oops, something went wrong.