Version 2.x

This commit is contained in:
Stef Heyenrath
2025-08-30 10:24:07 +02:00
parent 358590918e
commit 034766a2d6
83 changed files with 1077 additions and 999 deletions

View File

@@ -4,7 +4,7 @@
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<Version>1.11.2</Version> <Version>2.0.0-preview-01</Version>
<PackageIcon>WireMock.Net-Logo.png</PackageIcon> <PackageIcon>WireMock.Net-Logo.png</PackageIcon>
<PackageProjectUrl>https://github.com/wiremock/WireMock.Net</PackageProjectUrl> <PackageProjectUrl>https://github.com/wiremock/WireMock.Net</PackageProjectUrl>
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression> <PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>
@@ -13,7 +13,7 @@
<RepositoryUrl>https://github.com/wiremock/WireMock.Net</RepositoryUrl> <RepositoryUrl>https://github.com/wiremock/WireMock.Net</RepositoryUrl>
<ApplicationIcon>../../resources/WireMock.Net-Logo.ico</ApplicationIcon> <ApplicationIcon>../../resources/WireMock.Net-Logo.ico</ApplicationIcon>
<PackageReadmeFile>PackageReadme.md</PackageReadmeFile> <PackageReadmeFile>PackageReadme.md</PackageReadmeFile>
<LangVersion>12.0</LangVersion> <LangVersion>13</LangVersion>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
@@ -51,17 +51,17 @@
<ItemGroup> <ItemGroup>
<!-- CVE-2019-0820 --> <!-- CVE-2019-0820 -->
<PackageReference Include="System.Text.RegularExpressions" Version="4.3.1" /> <!--<PackageReference Include="System.Text.RegularExpressions" Version="4.3.1" />-->
<PackageReference Include="JetBrains.Annotations" Version="2024.3.0" PrivateAssets="All" /> <PackageReference Include="JetBrains.Annotations" Version="2024.3.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" PrivateAssets="All" /> <PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' "> <ItemGroup Condition=" '$(TargetFramework)' == 'net8.0' ">
<PackageReference Include="SonarAnalyzer.CSharp" Version="10.15.0.120848"> <!--<PackageReference Include="SonarAnalyzer.CSharp" Version="10.15.0.120848">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>-->
<!-- <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556"> <!-- <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>

View File

@@ -123,7 +123,7 @@ public class SettingsModel
/// </summary> /// </summary>
public Dictionary<string, string[]>? ProtoDefinitions { get; set; } public Dictionary<string, string[]>? ProtoDefinitions { get; set; }
#if NETSTANDARD1_3_OR_GREATER || NET461 //#if NETSTANDARD1_3_OR_GREATER || NET461
/// <summary> /// <summary>
/// Server client certificate mode /// Server client certificate mode
/// </summary> /// </summary>
@@ -133,5 +133,5 @@ public class SettingsModel
/// Whether to accept any client certificate /// Whether to accept any client certificate
/// </summary> /// </summary>
public bool AcceptAnyClientCertificate { get; set; } public bool AcceptAnyClientCertificate { get; set; }
#endif //#endif
} }

View File

@@ -2,9 +2,10 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
#if NETSTANDARD1_3_OR_GREATER || NET461
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
#endif //#if NETSTANDARD1_3_OR_GREATER || NET461
//using System.Security.Cryptography.X509Certificates;
//#endif
using WireMock.Types; using WireMock.Types;
using WireMock.Util; using WireMock.Util;
@@ -118,13 +119,13 @@ public interface IRequestMessage
/// </summary> /// </summary>
byte[]? BodyAsBytes { get; } byte[]? BodyAsBytes { get; }
#if MIMEKIT //#if MIMEKIT
/// <summary> /// <summary>
/// The original body as MimeMessage. /// The original body as MimeMessage.
/// Convenience getter for Handlebars and WireMockAssertions. /// Convenience getter for Handlebars and WireMockAssertions.
/// </summary> /// </summary>
Models.Mime.IMimeMessageData? BodyAsMimeMessage { get; } Models.Mime.IMimeMessageData? BodyAsMimeMessage { get; }
#endif //#endif
/// <summary> /// <summary>
/// The detected body type. Convenience getter for Handlebars. /// The detected body type. Convenience getter for Handlebars.
@@ -169,10 +170,10 @@ public interface IRequestMessage
/// <returns>The query parameter value as WireMockList or null when not found.</returns> /// <returns>The query parameter value as WireMockList or null when not found.</returns>
WireMockList<string>? GetParameter(string key, bool ignoreCase = false); WireMockList<string>? GetParameter(string key, bool ignoreCase = false);
#if NETSTANDARD1_3_OR_GREATER || NET461 //#if NETSTANDARD1_3_OR_GREATER || NET461
/// <summary> /// <summary>
/// Gets the connection's client certificate /// Gets the connection's client certificate
/// </summary> /// </summary>
X509Certificate2? ClientCertificate { get; } X509Certificate2? ClientCertificate { get; }
#endif //#endif
} }

View File

@@ -2,7 +2,7 @@
namespace WireMock.Types; namespace WireMock.Types;
#if NETSTANDARD1_3_OR_GREATER || NET461 //#if NETSTANDARD1_3_OR_GREATER || NET461
/// <summary> /// <summary>
/// Describes the client certificate requirements for a HTTPS connection. /// Describes the client certificate requirements for a HTTPS connection.
/// This enum is the same as https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.server.kestrel.https.clientcertificatemode /// This enum is the same as https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.server.kestrel.https.clientcertificatemode
@@ -30,4 +30,4 @@ public enum ClientCertificateMode
/// </summary> /// </summary>
DelayCertificate, DelayCertificate,
} }
#endif //#endif

View File

@@ -4,7 +4,8 @@
<Description>Commonly used interfaces, models, enumerations and types.</Description> <Description>Commonly used interfaces, models, enumerations and types.</Description>
<AssemblyTitle>WireMock.Net.Abstractions</AssemblyTitle> <AssemblyTitle>WireMock.Net.Abstractions</AssemblyTitle>
<Authors>Stef Heyenrath</Authors> <Authors>Stef Heyenrath</Authors>
<TargetFrameworks>net45;net451;net461;netstandard1.3;netstandard2.0;netstandard2.1</TargetFrameworks> <!--<TargetFrameworks>net45;net451;net461;netstandard1.3;netstandard2.0;netstandard2.1</TargetFrameworks>-->
<TargetFrameworks>net48;net8.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591;8603</NoWarn> <NoWarn>$(NoWarn);1591;8603</NoWarn>
<AssemblyName>WireMock.Net.Abstractions</AssemblyName> <AssemblyName>WireMock.Net.Abstractions</AssemblyName>
@@ -33,32 +34,36 @@
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' or '$(TargetFramework)' == 'netstandard2.1'"> <!--<PropertyGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' or '$(TargetFramework)' == 'netstandard2.1'">
<DefineConstants>$(DefineConstants);GRAPHQL;MIMEKIT;PROTOBUF</DefineConstants> <DefineConstants>$(DefineConstants);GRAPHQL;MIMEKIT;PROTOBUF</DefineConstants>
</PropertyGroup> </PropertyGroup>-->
<ItemGroup> <ItemGroup Condition=" '$(TargetFramework)' == 'net48' ">
<!-- CVE-2018-8292 / https://github.com/advisories/GHSA-7jgj-8wvc-jh57 --> <!-- CVE-2018-8292 / https://github.com/advisories/GHSA-7jgj-8wvc-jh57 -->
<PackageReference Include="System.Net.Http " Version="4.3.4" /> <PackageReference Include="System.Net.Http " Version="4.3.4" />
<!-- See also https://mstack.nl/blog/20210801-source-generators -->
<PackageReference Include="FluentBuilder" Version="0.10.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="PolySharp" Version="1.15.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup> </ItemGroup>
<ItemGroup Condition="$(TargetFramework.StartsWith('netstandard')) and '$(TargetFramework)' != 'netstandard1.0'"> <ItemGroup>
<PackageReference Include="FluentBuilder" Version="0.12.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Polyfill" Version="8.8.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<!--<PackageReference Include="PolySharp" Version="1.15.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>-->
</ItemGroup>
<!--<ItemGroup Condition="$(TargetFramework.StartsWith('netstandard')) and '$(TargetFramework)' != 'netstandard1.0'">
<PackageReference Include="System.Security.Cryptography.X509Certificates" Version="4.3.0" /> <PackageReference Include="System.Security.Cryptography.X509Certificates" Version="4.3.0" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard1.3' or '$(TargetFramework)' == 'net45' or '$(TargetFramework)' == 'net451' or '$(TargetFramework)' == 'net461'"> <ItemGroup Condition="'$(TargetFramework)' == 'netstandard1.3' or '$(TargetFramework)' == 'net45' or '$(TargetFramework)' == 'net451' or '$(TargetFramework)' == 'net461'">
<PackageReference Include="System.ValueTuple" Version="4.5.0" /> <PackageReference Include="System.ValueTuple" Version="4.5.0" />
</ItemGroup> </ItemGroup>-->
</Project> </Project>

View File

@@ -38,7 +38,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -1,10 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<Description>AwesomeAssertions extensions for WireMock.Net</Description> <Description>AwesomeAssertions extensions for WireMock.Net</Description>
<AssemblyTitle>WireMock.Net.AwesomeAssertions</AssemblyTitle> <AssemblyTitle>WireMock.Net.AwesomeAssertions</AssemblyTitle>
<Authors>Francesco Venturoli;Mahmoud Ali;Stef Heyenrath</Authors> <Authors>Francesco Venturoli;Mahmoud Ali;Stef Heyenrath</Authors>
<TargetFrameworks>net47;netstandard2.0;netstandard2.1</TargetFrameworks> <!--<TargetFrameworks>net47;netstandard2.0;netstandard2.1</TargetFrameworks>-->
<TargetFrameworks>net48;net8.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<AssemblyName>WireMock.Net.AwesomeAssertions</AssemblyName> <AssemblyName>WireMock.Net.AwesomeAssertions</AssemblyName>
<PackageId>WireMock.Net.AwesomeAssertions</PackageId> <PackageId>WireMock.Net.AwesomeAssertions</PackageId>

View File

@@ -25,10 +25,10 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="JsonConverter.Newtonsoft.Json" Version="0.7.0" /> <PackageReference Include="JsonConverter.Newtonsoft.Json" Version="0.7.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\WireMock.Net.Minimal\WireMock.Net.Minimal.csproj" /> <ProjectReference Include="..\WireMock.Net.Minimal\WireMock.Net.Minimal.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -1,10 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<Description>FluentAssertions extensions for WireMock.Net</Description> <Description>FluentAssertions extensions for WireMock.Net</Description>
<AssemblyTitle>WireMock.Net.FluentAssertions</AssemblyTitle> <AssemblyTitle>WireMock.Net.FluentAssertions</AssemblyTitle>
<Authors>Mahmoud Ali;Stef Heyenrath</Authors> <Authors>Mahmoud Ali;Stef Heyenrath</Authors>
<TargetFrameworks>net451;net47;netstandard1.3;netstandard2.0;netstandard2.1</TargetFrameworks> <!--<TargetFrameworks>net451;net47;netstandard1.3;netstandard2.0;netstandard2.1</TargetFrameworks>-->
<TargetFrameworks>net48;net8.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<AssemblyName>WireMock.Net.FluentAssertions</AssemblyName> <AssemblyName>WireMock.Net.FluentAssertions</AssemblyName>
<PackageId>WireMock.Net.FluentAssertions</PackageId> <PackageId>WireMock.Net.FluentAssertions</PackageId>
@@ -31,12 +32,12 @@
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
</PropertyGroup> </PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net451' or '$(TargetFramework)' == 'netstandard1.3'"> <!--<ItemGroup Condition="'$(TargetFramework)' == 'net451' or '$(TargetFramework)' == 'netstandard1.3'">
<PackageReference Include="FluentAssertions" Version="5.10.3" /> <PackageReference Include="FluentAssertions" Version="5.10.3" />
</ItemGroup> </ItemGroup>-->
<ItemGroup Condition="'$(TargetFramework)' != 'net451' and '$(TargetFramework)' != 'netstandard1.3'"> <ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.5.1" /> <PackageReference Include="FluentAssertions" Version="7.2.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -4,7 +4,8 @@
<Description>GraphQL support for WireMock.Net</Description> <Description>GraphQL support for WireMock.Net</Description>
<AssemblyTitle>WireMock.Net.Matchers.GraphQL</AssemblyTitle> <AssemblyTitle>WireMock.Net.Matchers.GraphQL</AssemblyTitle>
<Authors>Stef Heyenrath</Authors> <Authors>Stef Heyenrath</Authors>
<TargetFrameworks>netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net8.0</TargetFrameworks> <!--<TargetFrameworks>netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net8.0</TargetFrameworks>-->
<TargetFrameworks>net48;net8.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageTags>wiremock;matchers;matcher;graphql</PackageTags> <PackageTags>wiremock;matchers;matcher;graphql</PackageTags>
<RootNamespace>WireMock</RootNamespace> <RootNamespace>WireMock</RootNamespace>
@@ -26,22 +27,22 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="GraphQL.NewtonsoftJson" Version="8.2.1" /> <PackageReference Include="GraphQL.NewtonsoftJson" Version="8.5.0" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' "> <!--<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
<PackageReference Include="System.Reflection.Emit" Version="4.3.0" /> <PackageReference Include="System.Reflection.Emit" Version="4.3.0" />
</ItemGroup> </ItemGroup>-->
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\WireMock.Net.Shared\WireMock.Net.Shared.csproj" /> <ProjectReference Include="..\WireMock.Net.Shared\WireMock.Net.Shared.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' "> <!--<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
<PackageReference Include="Nullable" Version="1.3.1"> <PackageReference Include="Nullable" Version="1.3.1">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
</ItemGroup> </ItemGroup>-->
</Project> </Project>

View File

@@ -108,72 +108,72 @@ public class CSharpCodeMatcher : ICSharpCodeMatcher
object? result; object? result;
#if (NET451 || NET452) //#if (NET451 || NET452)
var compilerParams = new System.CodeDom.Compiler.CompilerParameters // var compilerParams = new System.CodeDom.Compiler.CompilerParameters
{ // {
GenerateInMemory = true, // GenerateInMemory = true,
GenerateExecutable = false, // GenerateExecutable = false,
ReferencedAssemblies = // ReferencedAssemblies =
{ // {
"System.dll", // "System.dll",
"System.Core.dll", // "System.Core.dll",
"Microsoft.CSharp.dll", // "Microsoft.CSharp.dll",
"Newtonsoft.Json.dll" // "Newtonsoft.Json.dll"
} // }
}; // };
using (var codeProvider = new Microsoft.CSharp.CSharpCodeProvider()) // using (var codeProvider = new Microsoft.CSharp.CSharpCodeProvider())
{ // {
var compilerResults = codeProvider.CompileAssemblyFromSource(compilerParams, source); // var compilerResults = codeProvider.CompileAssemblyFromSource(compilerParams, source);
if (compilerResults.Errors.Count != 0) // if (compilerResults.Errors.Count != 0)
{ // {
var errors = from System.CodeDom.Compiler.CompilerError er in compilerResults.Errors select er.ToString(); // var errors = from System.CodeDom.Compiler.CompilerError er in compilerResults.Errors select er.ToString();
throw new WireMockException(string.Join(", ", errors)); // throw new WireMockException(string.Join(", ", errors));
} // }
var helper = compilerResults.CompiledAssembly?.CreateInstance("CodeHelper"); // var helper = compilerResults.CompiledAssembly?.CreateInstance("CodeHelper");
if (helper == null) // if (helper == null)
{ // {
throw new WireMockException("CSharpCodeMatcher: Unable to create instance from WireMock.CodeHelper"); // throw new WireMockException("CSharpCodeMatcher: Unable to create instance from WireMock.CodeHelper");
} // }
var methodInfo = helper.GetType().GetMethod("IsMatch"); // var methodInfo = helper.GetType().GetMethod("IsMatch");
if (methodInfo == null) // if (methodInfo == null)
{ // {
throw new WireMockException("CSharpCodeMatcher: Unable to find method 'IsMatch' in WireMock.CodeHelper"); // throw new WireMockException("CSharpCodeMatcher: Unable to find method 'IsMatch' in WireMock.CodeHelper");
} // }
try // try
{ // {
result = methodInfo.Invoke(helper, new[] { inputValue }); // result = methodInfo.Invoke(helper, new[] { inputValue });
} // }
catch (Exception ex) // catch (Exception ex)
{ // {
throw new WireMockException("CSharpCodeMatcher: Unable to call method 'IsMatch' in WireMock.CodeHelper", ex); // throw new WireMockException("CSharpCodeMatcher: Unable to call method 'IsMatch' in WireMock.CodeHelper", ex);
} // }
} // }
#elif (NET46 || NET461) //#elif (NET46 || NET461)
dynamic script; // dynamic script;
try // try
{ // {
script = CSScriptLibrary.CSScript.Evaluator.CompileCode(source).CreateObject("*"); // script = CSScriptLibrary.CSScript.Evaluator.CompileCode(source).CreateObject("*");
} // }
catch (Exception ex) // catch (Exception ex)
{ // {
throw new WireMockException("CSharpCodeMatcher: Unable to create compiler for WireMock.CodeHelper", ex); // throw new WireMockException("CSharpCodeMatcher: Unable to create compiler for WireMock.CodeHelper", ex);
} // }
try // try
{ // {
result = script.IsMatch(inputValue); // result = script.IsMatch(inputValue);
} // }
catch (Exception ex) // catch (Exception ex)
{ // {
throw new WireMockException("CSharpCodeMatcher: Problem calling method 'IsMatch' in WireMock.CodeHelper", ex); // throw new WireMockException("CSharpCodeMatcher: Problem calling method 'IsMatch' in WireMock.CodeHelper", ex);
} // }
#elif (NETSTANDARD2_0 || NETSTANDARD2_1 || NETCOREAPP3_1 || NET5_0_OR_GREATER) //#elif (NETSTANDARD2_0 || NETSTANDARD2_1 || NETCOREAPP3_1 || NET5_0_OR_GREATER || NET48)
Assembly assembly; Assembly assembly;
try try
{ {
@@ -202,9 +202,9 @@ public class CSharpCodeMatcher : ICSharpCodeMatcher
{ {
throw new WireMockException("CSharpCodeMatcher: Problem calling method 'IsMatch' in WireMock.CodeHelper", ex); throw new WireMockException("CSharpCodeMatcher: Problem calling method 'IsMatch' in WireMock.CodeHelper", ex);
} }
#else //#else
throw new NotSupportedException("The 'CSharpCodeMatcher' cannot be used in netstandard 1.3"); // throw new NotSupportedException("The 'CSharpCodeMatcher' cannot be used in netstandard 1.3");
#endif //#endif
try try
{ {
return (bool)result; return (bool)result;

View File

@@ -4,7 +4,8 @@
<Description>A CSharpCodeMatcher which can be used to match WireMock.Net Requests using C# code.</Description> <Description>A CSharpCodeMatcher which can be used to match WireMock.Net Requests using C# code.</Description>
<AssemblyTitle>WireMock.Net.Matchers.CSharpCode</AssemblyTitle> <AssemblyTitle>WireMock.Net.Matchers.CSharpCode</AssemblyTitle>
<Authors>Stef Heyenrath</Authors> <Authors>Stef Heyenrath</Authors>
<TargetFrameworks>net451;net452;net46;net461;netstandard1.3;netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0</TargetFrameworks> <!--<TargetFrameworks>net451;net452;net46;net461;netstandard1.3;netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0</TargetFrameworks>-->
<TargetFrameworks>net48;net8.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageTags>wiremock;matchers;matcher;csharp;csharpcode</PackageTags> <PackageTags>wiremock;matchers;matcher;csharp;csharpcode</PackageTags>
<RootNamespace>WireMock</RootNamespace> <RootNamespace>WireMock</RootNamespace>
@@ -37,7 +38,7 @@
<ProjectReference Include="..\WireMock.Net.Minimal\WireMock.Net.Minimal.csproj" /> <ProjectReference Include="..\WireMock.Net.Minimal\WireMock.Net.Minimal.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net451' or '$(TargetFramework)' == 'net452' "> <!--<ItemGroup Condition=" '$(TargetFramework)' == 'net451' or '$(TargetFramework)' == 'net452' ">
<PackageReference Include="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" Version="3.6.0" /> <PackageReference Include="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" Version="3.6.0" />
</ItemGroup> </ItemGroup>
@@ -47,6 +48,10 @@
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' or '$(TargetFramework)' == 'netstandard2.1' or '$(TargetFramework)' == 'netcoreapp3.1' or '$(TargetFramework)' == 'net5.0' or '$(TargetFramework)' == 'net6.0' or '$(TargetFramework)' == 'net7.0' or '$(TargetFramework)' == 'net8.0'"> <ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' or '$(TargetFramework)' == 'netstandard2.1' or '$(TargetFramework)' == 'netcoreapp3.1' or '$(TargetFramework)' == 'net5.0' or '$(TargetFramework)' == 'net6.0' or '$(TargetFramework)' == 'net7.0' or '$(TargetFramework)' == 'net8.0'">
<PackageReference Include="CS-Script" Version="4.8.17" /> <PackageReference Include="CS-Script" Version="4.8.17" />
</ItemGroup>-->
<ItemGroup>
<PackageReference Include="CS-Script" Version="4.11.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -135,6 +135,6 @@ internal class MimeMessageDataWrapper : IMimeMessageData
/// <inheritdoc/> /// <inheritdoc/>
public override string ToString() public override string ToString()
{ {
return _message.ToString(); return _message.ToString() ?? string.Empty;
} }
} }

View File

@@ -4,7 +4,8 @@
<Description>MultiPart Mime support for WireMock.Net using MimeKitLite</Description> <Description>MultiPart Mime support for WireMock.Net using MimeKitLite</Description>
<AssemblyTitle>WireMock.Net.MimePart</AssemblyTitle> <AssemblyTitle>WireMock.Net.MimePart</AssemblyTitle>
<Authors>Stef Heyenrath</Authors> <Authors>Stef Heyenrath</Authors>
<TargetFrameworks>netstandard2.0;netstandard2.1;net462;net47;net48;net6.0;net8.0</TargetFrameworks> <!--<TargetFrameworks>netstandard2.0;netstandard2.1;net462;net47;net48;net6.0;net8.0</TargetFrameworks>-->
<TargetFrameworks>net48;net8.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageTags>wiremock;matchers;matcher;mime;multipart;mimekit</PackageTags> <PackageTags>wiremock;matchers;matcher;mime;multipart;mimekit</PackageTags>
<RootNamespace>WireMock</RootNamespace> <RootNamespace>WireMock</RootNamespace>
@@ -36,11 +37,11 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Nullable" Version="1.3.1"> <!--<PackageReference Include="Nullable" Version="1.3.1">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>-->
<PackageReference Include="Stef.Validation" Version="0.1.1" /> <PackageReference Include="Stef.Validation" Version="0.2.0" />
</ItemGroup> </ItemGroup>
<!--<ItemGroup> <!--<ItemGroup>
@@ -48,12 +49,12 @@
</ItemGroup>--> </ItemGroup>-->
<ItemGroup Condition="'$(Configuration)' == 'Debug'"> <ItemGroup Condition="'$(Configuration)' == 'Debug'">
<PackageReference Include="MimeKitLite" Version="4.12.0" /> <PackageReference Include="MimeKitLite" Version="4.13.0" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition="'$(Configuration)' == 'Release'"> <ItemGroup Condition="'$(Configuration)' == 'Release'">
<PackageReference Include="ILRepack.Lib.MSBuild.Task" Version="2.0.40" PrivateAssets="All" /> <PackageReference Include="ILRepack.Lib.MSBuild.Task" Version="2.0.40" PrivateAssets="All" />
<PackageReference Include="MimeKitLite" Version="4.12.0" PrivateAssets="All" /> <PackageReference Include="MimeKitLite" Version="4.13.0" PrivateAssets="All" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -1,6 +1,6 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
#if NET451 || NET452 || NET46 || NET451 || NET461 || NETSTANDARD1_3 || NETSTANDARD2_0 #if NET451 || NET452 || NET46 || NET461 || NET48 || NETSTANDARD1_3 || NETSTANDARD2_0
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using WireMock.Constants; using WireMock.Constants;

View File

@@ -11,24 +11,18 @@ internal static class HttpClientBuilder
{ {
public static HttpClient Build(HttpClientSettings settings) public static HttpClient Build(HttpClientSettings settings)
{ {
#if NETSTANDARD || NETCOREAPP3_1 || NET5_0_OR_GREATER #if NET8_0_OR_GREATER
var handler = new HttpClientHandler var handler = new HttpClientHandler
{ {
CheckCertificateRevocationList = false, CheckCertificateRevocationList = false,
SslProtocols = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls, SslProtocols = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls,
ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true, ServerCertificateCustomValidationCallback = (_, _, _, _) => true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
#elif NET46
var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
}; };
#else #else
var handler = new WebRequestHandler var handler = new HttpClientHandler
{ {
ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true, ServerCertificateCustomValidationCallback = (_, _, _, _) => true,
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
}; };
#endif #endif

View File

@@ -1,6 +1,6 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
#if NETCOREAPP3_1 || NET5_0_OR_GREATER #if NET8_0
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using WireMock.Types; using WireMock.Types;

View File

@@ -1,12 +1,11 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
#if USE_ASPNETCORE && !NETSTANDARD1_3 //#if USE_ASPNETCORE && !NETSTANDARD1_3
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Server.Kestrel.Https;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using CertificateLoader = WireMock.HttpsCertificate.CertificateLoader; using CertificateLoader = WireMock.HttpsCertificate.CertificateLoader;
@@ -38,7 +37,7 @@ internal partial class AspNetCoreSelfHost
options.ServerCertificate = CertificateLoader.LoadCertificate(wireMockMiddlewareOptions, urlDetail.Host); options.ServerCertificate = CertificateLoader.LoadCertificate(wireMockMiddlewareOptions, urlDetail.Host);
} }
options.ClientCertificateMode = (ClientCertificateMode)wireMockMiddlewareOptions.ClientCertificateMode; options.ClientCertificateMode = wireMockMiddlewareOptions.ClientCertificateMode;
if (wireMockMiddlewareOptions.AcceptAnyClientCertificate) if (wireMockMiddlewareOptions.AcceptAnyClientCertificate)
{ {
options.ClientCertificateValidation = (_, _, _) => true; options.ClientCertificateValidation = (_, _, _) => true;
@@ -47,7 +46,7 @@ internal partial class AspNetCoreSelfHost
if (urlDetail.IsHttp2) if (urlDetail.IsHttp2)
{ {
listenOptions.Protocols = HttpProtocols.Http2; SetHttp2AsProtocolsOnListenOptions(listenOptions);
} }
}); });
continue; continue;
@@ -55,10 +54,7 @@ internal partial class AspNetCoreSelfHost
if (urlDetail.IsHttp2) if (urlDetail.IsHttp2)
{ {
Listen(kestrelOptions, urlDetail, listenOptions => Listen(kestrelOptions, urlDetail, SetHttp2AsProtocolsOnListenOptions);
{
listenOptions.Protocols = HttpProtocols.Http2;
});
continue; continue;
} }
@@ -66,6 +62,15 @@ internal partial class AspNetCoreSelfHost
} }
} }
private static void SetHttp2AsProtocolsOnListenOptions(ListenOptions listenOptions)
{
#if NET8_0_OR_GREATER
listenOptions.Protocols = HttpProtocols.Http2;
#else
throw new NotSupportedException("HTTP/2 is only supported in .NET 8 or greater.");
#endif
}
private static void Listen(KestrelServerOptions kestrelOptions, HostUrlDetails urlDetail, Action<ListenOptions> configure) private static void Listen(KestrelServerOptions kestrelOptions, HostUrlDetails urlDetail, Action<ListenOptions> configure)
{ {
// Listens on any IP with the given port. // Listens on any IP with the given port.
@@ -112,4 +117,4 @@ internal static class IWebHostBuilderExtensions
}); });
} }
} }
#endif //#endif

View File

@@ -1,57 +1,57 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
#if USE_ASPNETCORE && NETSTANDARD1_3 //#if USE_ASPNETCORE && NETSTANDARD1_3
using System.Collections.Generic; //using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting; //using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel; //using Microsoft.AspNetCore.Server.Kestrel;
using Microsoft.AspNetCore.Server.Kestrel.Https; //using Microsoft.AspNetCore.Server.Kestrel.Https;
using Microsoft.Extensions.Configuration; //using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; //using Microsoft.Extensions.DependencyInjection;
using WireMock.HttpsCertificate; //using WireMock.HttpsCertificate;
namespace WireMock.Owin; //namespace WireMock.Owin;
internal partial class AspNetCoreSelfHost //internal partial class AspNetCoreSelfHost
{ //{
private static void SetKestrelOptionsLimits(KestrelServerOptions options) // private static void SetKestrelOptionsLimits(KestrelServerOptions options)
{ // {
options.Limits.MaxRequestBufferSize = null; // options.Limits.MaxRequestBufferSize = null;
options.Limits.MaxRequestHeaderCount = 100; // options.Limits.MaxRequestHeaderCount = 100;
options.Limits.MaxResponseBufferSize = null; // options.Limits.MaxResponseBufferSize = null;
} // }
private static void SetHttpsAndUrls(KestrelServerOptions options, IWireMockMiddlewareOptions wireMockMiddlewareOptions, IEnumerable<HostUrlDetails> urlDetails) // private static void SetHttpsAndUrls(KestrelServerOptions options, IWireMockMiddlewareOptions wireMockMiddlewareOptions, IEnumerable<HostUrlDetails> urlDetails)
{ // {
foreach (var urlDetail in urlDetails) // foreach (var urlDetail in urlDetails)
{ // {
if (urlDetail.IsHttps) // if (urlDetail.IsHttps)
{ // {
options.UseHttps(new HttpsConnectionFilterOptions // options.UseHttps(new HttpsConnectionFilterOptions
{ // {
ServerCertificate = wireMockMiddlewareOptions.CustomCertificateDefined ? CertificateLoader.LoadCertificate(wireMockMiddlewareOptions, urlDetail.Host) : PublicCertificateHelper.GetX509Certificate2(), // ServerCertificate = wireMockMiddlewareOptions.CustomCertificateDefined ? CertificateLoader.LoadCertificate(wireMockMiddlewareOptions, urlDetail.Host) : PublicCertificateHelper.GetX509Certificate2(),
ClientCertificateMode = (ClientCertificateMode) wireMockMiddlewareOptions.ClientCertificateMode, // ClientCertificateMode = (ClientCertificateMode) wireMockMiddlewareOptions.ClientCertificateMode,
ClientCertificateValidation = wireMockMiddlewareOptions.AcceptAnyClientCertificate ? (_, _, _) => true : null // ClientCertificateValidation = wireMockMiddlewareOptions.AcceptAnyClientCertificate ? (_, _, _) => true : null
}); // });
} // }
} // }
} // }
} //}
internal static class IWebHostBuilderExtensions //internal static class IWebHostBuilderExtensions
{ //{
internal static IWebHostBuilder ConfigureAppConfigurationUsingEnvironmentVariables(this IWebHostBuilder builder) => builder; // internal static IWebHostBuilder ConfigureAppConfigurationUsingEnvironmentVariables(this IWebHostBuilder builder) => builder;
internal static IWebHostBuilder ConfigureKestrelServerOptions(this IWebHostBuilder builder) // internal static IWebHostBuilder ConfigureKestrelServerOptions(this IWebHostBuilder builder)
{ // {
var configuration = new ConfigurationBuilder() // var configuration = new ConfigurationBuilder()
.AddEnvironmentVariables() // .AddEnvironmentVariables()
.Build(); // .Build();
return builder.ConfigureServices(services => // return builder.ConfigureServices(services =>
{ // {
services.Configure<KestrelServerOptions>(configuration.GetSection("Kestrel")); // services.Configure<KestrelServerOptions>(configuration.GetSection("Kestrel"));
}); // });
} // }
} //}
#endif //#endif

View File

@@ -1,10 +1,9 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
#if USE_ASPNETCORE //#if USE_ASPNETCORE
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
@@ -74,7 +73,7 @@ internal partial class AspNetCoreSelfHost : IOwinSelfHost
services.AddSingleton<IOwinResponseMapper, OwinResponseMapper>(); services.AddSingleton<IOwinResponseMapper, OwinResponseMapper>();
services.AddSingleton<IGuidUtils, GuidUtils>(); services.AddSingleton<IGuidUtils, GuidUtils>();
#if NETCOREAPP3_1 || NET5_0_OR_GREATER #if NET8_0_OR_GREATER
AddCors(services); AddCors(services);
#endif #endif
_wireMockMiddlewareOptions.AdditionalServiceRegistration?.Invoke(services); _wireMockMiddlewareOptions.AdditionalServiceRegistration?.Invoke(services);
@@ -83,7 +82,7 @@ internal partial class AspNetCoreSelfHost : IOwinSelfHost
{ {
appBuilder.UseMiddleware<GlobalExceptionMiddleware>(); appBuilder.UseMiddleware<GlobalExceptionMiddleware>();
#if NETCOREAPP3_1 || NET5_0_OR_GREATER #if NET8_0_OR_GREATER
UseCors(appBuilder); UseCors(appBuilder);
#endif #endif
_wireMockMiddlewareOptions.PreWireMockMiddlewareInit?.Invoke(appBuilder); _wireMockMiddlewareOptions.PreWireMockMiddlewareInit?.Invoke(appBuilder);
@@ -100,9 +99,9 @@ internal partial class AspNetCoreSelfHost : IOwinSelfHost
}) })
.ConfigureKestrelServerOptions() .ConfigureKestrelServerOptions()
#if NETSTANDARD1_3 //#if NETSTANDARD1_3
.UseUrls(_urlOptions.GetDetails().Select(u => u.Url).ToArray()) // .UseUrls(_urlOptions.GetDetails().Select(u => u.Url).ToArray())
#endif //#endif
.Build(); .Build();
return RunHost(_cts.Token); return RunHost(_cts.Token);
@@ -112,7 +111,7 @@ internal partial class AspNetCoreSelfHost : IOwinSelfHost
{ {
try try
{ {
#if NETCOREAPP3_1 || NET5_0_OR_GREATER #if NET8_0_OR_GREATER
var appLifetime = _host.Services.GetRequiredService<Microsoft.Extensions.Hosting.IHostApplicationLifetime>(); var appLifetime = _host.Services.GetRequiredService<Microsoft.Extensions.Hosting.IHostApplicationLifetime>();
#else #else
var appLifetime = _host.Services.GetRequiredService<IApplicationLifetime>(); var appLifetime = _host.Services.GetRequiredService<IApplicationLifetime>();
@@ -134,23 +133,9 @@ internal partial class AspNetCoreSelfHost : IOwinSelfHost
IsStarted = true; IsStarted = true;
}); });
#if NETSTANDARD1_3 #if NET8_0
_logger.Info("Server using netstandard1.3");
#elif NETSTANDARD2_0
_logger.Info("Server using netstandard2.0");
#elif NETSTANDARD2_1
_logger.Info("Server using netstandard2.1");
#elif NETCOREAPP3_1
_logger.Info("Server using .NET Core App 3.1");
#elif NET5_0
_logger.Info("Server using .NET 5.0");
#elif NET6_0
_logger.Info("Server using .NET 6.0");
#elif NET7_0
_logger.Info("Server using .NET 7.0");
#elif NET8_0
_logger.Info("Server using .NET 8.0"); _logger.Info("Server using .NET 8.0");
#elif NET46 #elif NET48
_logger.Info("Server using .NET Framework 4.6.1 or higher"); _logger.Info("Server using .NET Framework 4.6.1 or higher");
#endif #endif
@@ -179,11 +164,11 @@ internal partial class AspNetCoreSelfHost : IOwinSelfHost
_cts.Cancel(); _cts.Cancel();
IsStarted = false; IsStarted = false;
#if NETSTANDARD1_3 //#if NETSTANDARD1_3
return Task.CompletedTask; // return Task.CompletedTask;
#else //#else
return _host.StopAsync(); return _host.StopAsync();
#endif //#endif
} }
} }
#endif //#endif

View File

@@ -3,68 +3,69 @@
using System; using System;
using System.Threading.Tasks; using System.Threading.Tasks;
using Newtonsoft.Json; using Newtonsoft.Json;
#if !USE_ASPNETCORE
using Microsoft.Owin;
using IContext = Microsoft.Owin.IOwinContext;
using OwinMiddleware = Microsoft.Owin.OwinMiddleware;
using Next = Microsoft.Owin.OwinMiddleware;
#else
using OwinMiddleware = System.Object;
using IContext = Microsoft.AspNetCore.Http.HttpContext;
using Next = Microsoft.AspNetCore.Http.RequestDelegate;
#endif
using WireMock.Owin.Mappers; using WireMock.Owin.Mappers;
using Stef.Validation; using Stef.Validation;
using Microsoft.AspNetCore.Http;
//#if !USE_ASPNETCORE
//using Microsoft.Owin;
//using IContext = Microsoft.Owin.IOwinContext;
//using OwinMiddleware = Microsoft.Owin.OwinMiddleware;
//using Next = Microsoft.Owin.OwinMiddleware;
//#else
//using OwinMiddleware = System.Object;
//using IContext = Microsoft.AspNetCore.Http.HttpContext;
//using Next = Microsoft.AspNetCore.Http.RequestDelegate;
//#endif
namespace WireMock.Owin
namespace WireMock.Owin;
internal class GlobalExceptionMiddleware //: OwinMiddleware
{ {
internal class GlobalExceptionMiddleware : OwinMiddleware private readonly IWireMockMiddlewareOptions _options;
private readonly IOwinResponseMapper _responseMapper;
//#if !USE_ASPNETCORE
// public GlobalExceptionMiddleware(Next next, IWireMockMiddlewareOptions options, IOwinResponseMapper responseMapper) : base(next)
// {
// _options = Guard.NotNull(options);
// _responseMapper = Guard.NotNull(responseMapper);;
// }
//#else
public GlobalExceptionMiddleware(RequestDelegate next, IWireMockMiddlewareOptions options, IOwinResponseMapper responseMapper)
{ {
private readonly IWireMockMiddlewareOptions _options; Next = next;
private readonly IOwinResponseMapper _responseMapper; _options = Guard.NotNull(options);
_responseMapper = Guard.NotNull(responseMapper);
}
//#endif
#if !USE_ASPNETCORE //#if USE_ASPNETCORE
public GlobalExceptionMiddleware(Next next, IWireMockMiddlewareOptions options, IOwinResponseMapper responseMapper) : base(next) public RequestDelegate? Next { get; }
{ //#endif
_options = Guard.NotNull(options);
_responseMapper = Guard.NotNull(responseMapper);;
}
#else
public GlobalExceptionMiddleware(Next next, IWireMockMiddlewareOptions options, IOwinResponseMapper responseMapper)
{
Next = next;
_options = Guard.NotNull(options);
_responseMapper = Guard.NotNull(responseMapper);
}
#endif
#if USE_ASPNETCORE //#if !USE_ASPNETCORE
public Next Next { get; } // public override Task Invoke(IContext ctx)
#endif //#else
public Task Invoke(HttpContext ctx)
//#endif
{
return InvokeInternalAsync(ctx);
}
#if !USE_ASPNETCORE private async Task InvokeInternalAsync(HttpContext ctx)
public override Task Invoke(IContext ctx) {
#else try
public Task Invoke(IContext ctx)
#endif
{ {
return InvokeInternalAsync(ctx); if (Next != null)
}
private async Task InvokeInternalAsync(IContext ctx)
{
try
{ {
if (Next != null) await Next.Invoke(ctx).ConfigureAwait(false);
{
await Next.Invoke(ctx).ConfigureAwait(false);
}
}
catch (Exception ex)
{
_options.Logger.Error("HttpStatusCode set to 500 {0}", ex);
await _responseMapper.MapAsync(ResponseMessageBuilder.Create(500, JsonConvert.SerializeObject(ex)), ctx.Response).ConfigureAwait(false);
} }
} }
catch (Exception ex)
{
_options.Logger.Error("HttpStatusCode set to 500 {0}", ex);
await _responseMapper.MapAsync(ResponseMessageBuilder.Create(500, JsonConvert.SerializeObject(ex)), ctx.Response).ConfigureAwait(false);
}
} }
} }

View File

@@ -2,21 +2,22 @@
using System; using System;
using System.Collections.Concurrent; using System.Collections.Concurrent;
using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using WireMock.Handlers; using WireMock.Handlers;
using WireMock.Logging; using WireMock.Logging;
using WireMock.Matchers; using WireMock.Matchers;
using WireMock.Types; using WireMock.Types;
using WireMock.Util; using WireMock.Util;
using System.Security.Cryptography.X509Certificates; using ClientCertificateMode = Microsoft.AspNetCore.Server.Kestrel.Https.ClientCertificateMode;
using JetBrains.Annotations; //#if !USE_ASPNETCORE
//using Owin;
#if !USE_ASPNETCORE //#else
using Owin; //using IAppBuilder = Microsoft.AspNetCore.Builder.IApplicationBuilder;
#else //using Microsoft.Extensions.DependencyInjection;
using IAppBuilder = Microsoft.AspNetCore.Builder.IApplicationBuilder; //#endif
using Microsoft.Extensions.DependencyInjection;
#endif
namespace WireMock.Owin; namespace WireMock.Owin;
@@ -40,11 +41,11 @@ internal interface IWireMockMiddlewareOptions
int? MaxRequestLogCount { get; set; } int? MaxRequestLogCount { get; set; }
Action<IAppBuilder>? PreWireMockMiddlewareInit { get; set; } Action<IApplicationBuilder>? PreWireMockMiddlewareInit { get; set; }
Action<IAppBuilder>? PostWireMockMiddlewareInit { get; set; } Action<IApplicationBuilder>? PostWireMockMiddlewareInit { get; set; }
#if USE_ASPNETCORE //#if USE_ASPNETCORE
Action<IServiceCollection>? AdditionalServiceRegistration { get; set; } Action<IServiceCollection>? AdditionalServiceRegistration { get; set; }
CorsPolicyOptions? CorsPolicyOptions { get; set; } CorsPolicyOptions? CorsPolicyOptions { get; set; }
@@ -52,7 +53,7 @@ internal interface IWireMockMiddlewareOptions
ClientCertificateMode ClientCertificateMode { get; set; } ClientCertificateMode ClientCertificateMode { get; set; }
bool AcceptAnyClientCertificate { get; set; } bool AcceptAnyClientCertificate { get; set; }
#endif //#endif
IFileSystemHandler? FileSystemHandler { get; set; } IFileSystemHandler? FileSystemHandler { get; set; }

View File

@@ -1,25 +1,25 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
using System.Threading.Tasks; using System.Threading.Tasks;
#if !USE_ASPNETCORE using Microsoft.AspNetCore.Http;
using IRequest = Microsoft.Owin.IOwinRequest; //#if !USE_ASPNETCORE
#else //using IRequest = Microsoft.Owin.IOwinRequest;
using IRequest = Microsoft.AspNetCore.Http.HttpRequest; //#else
#endif //using IRequest = Microsoft.AspNetCore.Http.HttpRequest;
//#endif
namespace WireMock.Owin.Mappers namespace WireMock.Owin.Mappers;
/// <summary>
/// IOwinRequestMapper
/// </summary>
internal interface IOwinRequestMapper
{ {
/// <summary> /// <summary>
/// IOwinRequestMapper /// MapAsync IRequest to RequestMessage
/// </summary> /// </summary>
internal interface IOwinRequestMapper /// <param name="request">The HttpRequest</param>
{ /// <param name="options">The WireMockMiddlewareOptions</param>
/// <summary> /// <returns>RequestMessage</returns>
/// MapAsync IRequest to RequestMessage Task<RequestMessage> MapAsync(HttpRequest request, IWireMockMiddlewareOptions options);
/// </summary>
/// <param name="request">The OwinRequest/HttpRequest</param>
/// <param name="options">The WireMockMiddlewareOptions</param>
/// <returns>RequestMessage</returns>
Task<RequestMessage> MapAsync(IRequest request, IWireMockMiddlewareOptions options);
}
} }

View File

@@ -1,11 +1,13 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
using System.Threading.Tasks; using System.Threading.Tasks;
#if !USE_ASPNETCORE using Microsoft.AspNetCore.Http;
using IResponse = Microsoft.Owin.IOwinResponse;
#else //#if !USE_ASPNETCORE
using IResponse = Microsoft.AspNetCore.Http.HttpResponse; //using IResponse = Microsoft.Owin.IOwinResponse;
#endif //#else
//using IResponse = Microsoft.AspNetCore.Http.HttpResponse;
//#endif
namespace WireMock.Owin.Mappers; namespace WireMock.Owin.Mappers;
@@ -18,6 +20,6 @@ internal interface IOwinResponseMapper
/// Map ResponseMessage to IResponse. /// Map ResponseMessage to IResponse.
/// </summary> /// </summary>
/// <param name="responseMessage">The ResponseMessage</param> /// <param name="responseMessage">The ResponseMessage</param>
/// <param name="response">The OwinResponse/HttpResponse</param> /// <param name="response">The HttpResponse</param>
Task MapAsync(IResponseMessage? responseMessage, IResponse response); Task MapAsync(IResponseMessage? responseMessage, HttpResponse response);
} }

View File

@@ -4,15 +4,17 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using WireMock.Http; using WireMock.Http;
using WireMock.Models; using WireMock.Models;
using WireMock.Util; using WireMock.Util;
#if !USE_ASPNETCORE //#if !USE_ASPNETCORE
using IRequest = Microsoft.Owin.IOwinRequest; //using IRequest = Microsoft.Owin.IOwinRequest;
#else //#else
using Microsoft.AspNetCore.Http.Extensions; //using Microsoft.AspNetCore.Http.Extensions;
using IRequest = Microsoft.AspNetCore.Http.HttpRequest; //using IRequest = Microsoft.AspNetCore.Http.HttpRequest;
#endif //#endif
namespace WireMock.Owin.Mappers; namespace WireMock.Owin.Mappers;
@@ -22,7 +24,7 @@ namespace WireMock.Owin.Mappers;
internal class OwinRequestMapper : IOwinRequestMapper internal class OwinRequestMapper : IOwinRequestMapper
{ {
/// <inheritdoc /> /// <inheritdoc />
public async Task<RequestMessage> MapAsync(IRequest request, IWireMockMiddlewareOptions options) public async Task<RequestMessage> MapAsync(HttpRequest request, IWireMockMiddlewareOptions options)
{ {
var (urlDetails, clientIP) = ParseRequest(request); var (urlDetails, clientIP) = ParseRequest(request);
@@ -83,12 +85,12 @@ internal class OwinRequestMapper : IOwinRequestMapper
}; };
} }
private static (UrlDetails UrlDetails, string ClientIP) ParseRequest(IRequest request) private static (UrlDetails UrlDetails, string ClientIP) ParseRequest(HttpRequest request)
{ {
#if !USE_ASPNETCORE //#if !USE_ASPNETCORE
var urlDetails = UrlUtils.Parse(request.Uri, request.PathBase); // var urlDetails = UrlUtils.Parse(request.Uri, request.PathBase);
var clientIP = request.RemoteIpAddress; // var clientIP = request.RemoteIpAddress;
#else //#else
var urlDetails = UrlUtils.Parse(new Uri(request.GetEncodedUrl()), request.PathBase); var urlDetails = UrlUtils.Parse(new Uri(request.GetEncodedUrl()), request.PathBase);
var connection = request.HttpContext.Connection; var connection = request.HttpContext.Connection;
@@ -105,7 +107,7 @@ internal class OwinRequestMapper : IOwinRequestMapper
{ {
clientIP = connection.RemoteIpAddress.ToString(); clientIP = connection.RemoteIpAddress.ToString();
} }
#endif //#endif
return (urlDetails, clientIP); return (urlDetails, clientIP);
} }
} }

View File

@@ -8,21 +8,22 @@ using System.Net;
using System.Reflection; using System.Reflection;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json; using Newtonsoft.Json;
using RandomDataGenerator.FieldOptions; using RandomDataGenerator.FieldOptions;
using RandomDataGenerator.Randomizers; using RandomDataGenerator.Randomizers;
using Stef.Validation;
using WireMock.Http; using WireMock.Http;
using WireMock.ResponseBuilders; using WireMock.ResponseBuilders;
using WireMock.Types; using WireMock.Types;
using Stef.Validation;
using WireMock.Util; using WireMock.Util;
#if !USE_ASPNETCORE //#if !USE_ASPNETCORE
using IResponse = Microsoft.Owin.IOwinResponse; //using IResponse = Microsoft.Owin.IOwinResponse;
#else //#else
using Microsoft.AspNetCore.Http; //using Microsoft.AspNetCore.Http;
using IResponse = Microsoft.AspNetCore.Http.HttpResponse; //using IResponse = Microsoft.AspNetCore.Http.HttpResponse;
#endif //#endif
namespace WireMock.Owin.Mappers namespace WireMock.Owin.Mappers
{ {
@@ -37,8 +38,8 @@ namespace WireMock.Owin.Mappers
private readonly Encoding _utf8NoBom = new UTF8Encoding(false); private readonly Encoding _utf8NoBom = new UTF8Encoding(false);
// https://msdn.microsoft.com/en-us/library/78h415ay(v=vs.110).aspx // https://msdn.microsoft.com/en-us/library/78h415ay(v=vs.110).aspx
private static readonly IDictionary<string, Action<IResponse, bool, WireMockList<string>>> ResponseHeadersToFix = private static readonly IDictionary<string, Action<HttpResponse, bool, WireMockList<string>>> ResponseHeadersToFix =
new Dictionary<string, Action<IResponse, bool, WireMockList<string>>>(StringComparer.OrdinalIgnoreCase) new Dictionary<string, Action<HttpResponse, bool, WireMockList<string>>>(StringComparer.OrdinalIgnoreCase)
{ {
{ HttpKnownHeaderNames.ContentType, (r, _, v) => r.ContentType = v.FirstOrDefault() }, { HttpKnownHeaderNames.ContentType, (r, _, v) => r.ContentType = v.FirstOrDefault() },
{ HttpKnownHeaderNames.ContentLength, (r, hasBody, v) => { HttpKnownHeaderNames.ContentLength, (r, hasBody, v) =>
@@ -62,7 +63,7 @@ namespace WireMock.Owin.Mappers
} }
/// <inheritdoc /> /// <inheritdoc />
public async Task MapAsync(IResponseMessage? responseMessage, IResponse response) public async Task MapAsync(IResponseMessage? responseMessage, HttpResponse response)
{ {
if (responseMessage == null) if (responseMessage == null)
{ {
@@ -128,7 +129,7 @@ namespace WireMock.Owin.Mappers
SetResponseTrailingHeaders(responseMessage, response); SetResponseTrailingHeaders(responseMessage, response);
} }
private static async Task HandleSseStringAsync(IResponseMessage responseMessage, IResponse response, IBodyData bodyData) private static async Task HandleSseStringAsync(IResponseMessage responseMessage, HttpResponse response, IBodyData bodyData)
{ {
if (bodyData.SseStringQueue == null) if (bodyData.SseStringQueue == null)
{ {
@@ -199,7 +200,7 @@ namespace WireMock.Owin.Mappers
return null; return null;
} }
private static void SetResponseHeaders(IResponseMessage responseMessage, bool hasBody, IResponse response) private static void SetResponseHeaders(IResponseMessage responseMessage, bool hasBody, HttpResponse response)
{ {
// Force setting the Date header (#577) // Force setting the Date header (#577)
AppendResponseHeader( AppendResponseHeader(
@@ -215,7 +216,7 @@ namespace WireMock.Owin.Mappers
var value = item.Value; var value = item.Value;
if (ResponseHeadersToFix.TryGetValue(headerName, out var action)) if (ResponseHeadersToFix.TryGetValue(headerName, out var action))
{ {
action?.Invoke(response, hasBody, value); action.Invoke(response, hasBody, value);
} }
else else
{ {
@@ -228,7 +229,7 @@ namespace WireMock.Owin.Mappers
} }
} }
private static void SetResponseTrailingHeaders(IResponseMessage responseMessage, IResponse response) private static void SetResponseTrailingHeaders(IResponseMessage responseMessage, HttpResponse response)
{ {
if (responseMessage.TrailingHeaders == null) if (responseMessage.TrailingHeaders == null)
{ {
@@ -236,13 +237,11 @@ namespace WireMock.Owin.Mappers
} }
#if TRAILINGHEADERS #if TRAILINGHEADERS
foreach (var item in responseMessage.TrailingHeaders) foreach (var (headerName, value) in responseMessage.TrailingHeaders)
{ {
var headerName = item.Key;
var value = item.Value;
if (ResponseHeadersToFix.TryGetValue(headerName, out var action)) if (ResponseHeadersToFix.TryGetValue(headerName, out var action))
{ {
action?.Invoke(response, false, value); action.Invoke(response, false, value);
} }
else else
{ {
@@ -256,13 +255,13 @@ namespace WireMock.Owin.Mappers
#endif #endif
} }
private static void AppendResponseHeader(IResponse response, string headerName, string[] values) private static void AppendResponseHeader(HttpResponse response, string headerName, string[] values)
{ {
#if !USE_ASPNETCORE //#if !USE_ASPNETCORE
response.Headers.AppendValues(headerName, values); // response.Headers.AppendValues(headerName, values);
#else //#else
response.Headers.Append(headerName, values); response.Headers.Append(headerName, values);
#endif //#endif
} }
} }
} }

View File

@@ -1,114 +1,112 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
#if !USE_ASPNETCORE //using Microsoft.Owin.Hosting;
using Microsoft.Owin.Hosting; //using Owin;
using Owin; //using System;
using System; //using System.Collections.Generic;
using System.Collections.Generic; //using System.Threading;
using System.Threading; //using System.Threading.Tasks;
using System.Threading.Tasks; //using JetBrains.Annotations;
using JetBrains.Annotations; //using WireMock.Logging;
using WireMock.Logging; //using WireMock.Owin.Mappers;
using WireMock.Owin.Mappers; //using Stef.Validation;
using Stef.Validation; //using WireMock.Services;
using WireMock.Services; //using WireMock.Util;
using WireMock.Util;
namespace WireMock.Owin; //namespace WireMock.Owin;
internal class OwinSelfHost : IOwinSelfHost //internal class OwinSelfHost : IOwinSelfHost
{ //{
private readonly IWireMockMiddlewareOptions _options; // private readonly IWireMockMiddlewareOptions _options;
private readonly CancellationTokenSource _cts = new(); // private readonly CancellationTokenSource _cts = new();
private readonly IWireMockLogger _logger; // private readonly IWireMockLogger _logger;
private Exception? _runningException; // private Exception? _runningException;
public OwinSelfHost(IWireMockMiddlewareOptions options, HostUrlOptions urlOptions) // public OwinSelfHost(IWireMockMiddlewareOptions options, HostUrlOptions urlOptions)
{ // {
Guard.NotNull(urlOptions); // Guard.NotNull(urlOptions);
_options = Guard.NotNull(options); // _options = Guard.NotNull(options);
_logger = options.Logger ?? new WireMockConsoleLogger(); // _logger = options.Logger ?? new WireMockConsoleLogger();
foreach (var detail in urlOptions.GetDetails()) // foreach (var detail in urlOptions.GetDetails())
{ // {
Urls.Add(detail.Url); // Urls.Add(detail.Url);
Ports.Add(detail.Port); // Ports.Add(detail.Port);
} // }
} // }
public bool IsStarted { get; private set; } // public bool IsStarted { get; private set; }
public List<string> Urls { get; } = new(); // public List<string> Urls { get; } = new();
public List<int> Ports { get; } = new(); // public List<int> Ports { get; } = new();
public Exception? RunningException => _runningException; // public Exception? RunningException => _runningException;
[PublicAPI] // [PublicAPI]
public Task StartAsync() // public Task StartAsync()
{ // {
return Task.Run(StartServers, _cts.Token); // return Task.Run(StartServers, _cts.Token);
} // }
[PublicAPI] // [PublicAPI]
public Task StopAsync() // public Task StopAsync()
{ // {
_cts.Cancel(); // _cts.Cancel();
return Task.FromResult(true); // return Task.FromResult(true);
} // }
private void StartServers() // private void StartServers()
{ // {
#if NET46 //#if NET46
_logger.Info("Server using .net 4.6"); // _logger.Info("Server using .net 4.6");
#else //#else
_logger.Info("Server using .net 4.5.x"); // _logger.Info("Server using .net 4.5.x");
#endif //#endif
var servers = new List<IDisposable>(); // var servers = new List<IDisposable>();
try // try
{ // {
var requestMapper = new OwinRequestMapper(); // var requestMapper = new OwinRequestMapper();
var responseMapper = new OwinResponseMapper(_options); // var responseMapper = new OwinResponseMapper(_options);
var matcher = new MappingMatcher(_options, new RandomizerDoubleBetween0And1()); // var matcher = new MappingMatcher(_options, new RandomizerDoubleBetween0And1());
var guidUtils = new GuidUtils(); // var guidUtils = new GuidUtils();
Action<IAppBuilder> startup = app => // Action<IAppBuilder> startup = app =>
{ // {
app.Use<GlobalExceptionMiddleware>(_options, responseMapper); // app.Use<GlobalExceptionMiddleware>(_options, responseMapper);
_options.PreWireMockMiddlewareInit?.Invoke(app); // _options.PreWireMockMiddlewareInit?.Invoke(app);
app.Use<WireMockMiddleware>(_options, requestMapper, responseMapper, matcher, guidUtils); // app.Use<WireMockMiddleware>(_options, requestMapper, responseMapper, matcher, guidUtils);
_options.PostWireMockMiddlewareInit?.Invoke(app); // _options.PostWireMockMiddlewareInit?.Invoke(app);
}; // };
foreach (var url in Urls) // foreach (var url in Urls)
{ // {
servers.Add(WebApp.Start(url, startup)); // servers.Add(WebApp.Start(url, startup));
} // }
IsStarted = true; // IsStarted = true;
// WaitHandle is signaled when the token is cancelled, // // WaitHandle is signaled when the token is cancelled,
// which will be more efficient than Thread.Sleep in while loop // // which will be more efficient than Thread.Sleep in while loop
_cts.Token.WaitHandle.WaitOne(); // _cts.Token.WaitHandle.WaitOne();
} // }
catch (Exception e) // catch (Exception e)
{ // {
// Expose exception of starting host, otherwise it's hard to be troubleshooting if keeping quiet // // Expose exception of starting host, otherwise it's hard to be troubleshooting if keeping quiet
// For example, WebApp.Start will fail with System.MissingMemberException if Microsoft.Owin.Host.HttpListener.dll is being located // // For example, WebApp.Start will fail with System.MissingMemberException if Microsoft.Owin.Host.HttpListener.dll is being located
// https://stackoverflow.com/questions/25090211/owin-httplistener-not-located/31369857 // // https://stackoverflow.com/questions/25090211/owin-httplistener-not-located/31369857
_runningException = e; // _runningException = e;
_logger.Error(e.ToString()); // _logger.Error(e.ToString());
} // }
finally // finally
{ // {
IsStarted = false; // IsStarted = false;
// Dispose all servers in finally block to make sure clean up allocated resource on error happening // // Dispose all servers in finally block to make sure clean up allocated resource on error happening
servers.ForEach(s => s.Dispose()); // servers.ForEach(s => s.Dispose());
} // }
} // }
} //}
#endif

View File

@@ -1,368 +1,368 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
using System; using System;
using System.Threading.Tasks; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Stef.Validation; using Stef.Validation;
using WireMock.Logging;
using WireMock.Matchers;
using WireMock.Http;
using WireMock.Owin.Mappers;
using WireMock.Serialization;
using WireMock.ResponseBuilders;
using WireMock.Settings;
using System.Collections.Generic;
using WireMock.Constants; using WireMock.Constants;
using WireMock.Exceptions; using WireMock.Exceptions;
using WireMock.Http;
using WireMock.Logging;
using WireMock.Matchers;
using WireMock.Owin.Mappers;
using WireMock.ResponseBuilders;
using WireMock.Serialization;
using WireMock.Settings;
using WireMock.Util; using WireMock.Util;
#if !USE_ASPNETCORE //#if !USE_ASPNETCORE
using IContext = Microsoft.Owin.IOwinContext; //using IContext = Microsoft.Owin.IOwinContext;
using OwinMiddleware = Microsoft.Owin.OwinMiddleware; //using OwinMiddleware = Microsoft.Owin.OwinMiddleware;
using Next = Microsoft.Owin.OwinMiddleware; //using Next = Microsoft.Owin.OwinMiddleware;
#else //#else
using OwinMiddleware = System.Object; //using OwinMiddleware = System.Object;
using IContext = Microsoft.AspNetCore.Http.HttpContext; //using IContext = Microsoft.AspNetCore.Http.HttpContext;
using Next = Microsoft.AspNetCore.Http.RequestDelegate; //using Next = Microsoft.AspNetCore.Http.RequestDelegate;
#endif //#endif
namespace WireMock.Owin namespace WireMock.Owin;
internal class WireMockMiddleware //: OwinMiddleware
{ {
internal class WireMockMiddleware : OwinMiddleware private readonly object _lock = new();
private static readonly Task CompletedTask = Task.FromResult(false);
private readonly IWireMockMiddlewareOptions _options;
private readonly IOwinRequestMapper _requestMapper;
private readonly IOwinResponseMapper _responseMapper;
private readonly IMappingMatcher _mappingMatcher;
private readonly LogEntryMapper _logEntryMapper;
private readonly IGuidUtils _guidUtils;
//#if !USE_ASPNETCORE
// public WireMockMiddleware(
// Next next,
// IWireMockMiddlewareOptions options,
// IOwinRequestMapper requestMapper,
// IOwinResponseMapper responseMapper,
// IMappingMatcher mappingMatcher,
// IGuidUtils guidUtils
// ) : base(next)
// {
// _options = Guard.NotNull(options);
// _requestMapper = Guard.NotNull(requestMapper);
// _responseMapper = Guard.NotNull(responseMapper);
// _mappingMatcher = Guard.NotNull(mappingMatcher);
// _logEntryMapper = new LogEntryMapper(options);
// _guidUtils = Guard.NotNull(guidUtils);
// }
//#else
public WireMockMiddleware(
RequestDelegate next,
IWireMockMiddlewareOptions options,
IOwinRequestMapper requestMapper,
IOwinResponseMapper responseMapper,
IMappingMatcher mappingMatcher,
IGuidUtils guidUtils
)
{ {
private readonly object _lock = new(); _options = Guard.NotNull(options);
private static readonly Task CompletedTask = Task.FromResult(false); _requestMapper = Guard.NotNull(requestMapper);
_responseMapper = Guard.NotNull(responseMapper);
_mappingMatcher = Guard.NotNull(mappingMatcher);
_logEntryMapper = new LogEntryMapper(options);
_guidUtils = Guard.NotNull(guidUtils);
}
//#endif
private readonly IWireMockMiddlewareOptions _options; //#if !USE_ASPNETCORE
private readonly IOwinRequestMapper _requestMapper; // public override Task Invoke(IContext ctx)
private readonly IOwinResponseMapper _responseMapper; //#else
private readonly IMappingMatcher _mappingMatcher; public Task Invoke(HttpContext ctx)
private readonly LogEntryMapper _logEntryMapper; //#endif
private readonly IGuidUtils _guidUtils; {
if (_options.HandleRequestsSynchronously.GetValueOrDefault(false))
#if !USE_ASPNETCORE
public WireMockMiddleware(
Next next,
IWireMockMiddlewareOptions options,
IOwinRequestMapper requestMapper,
IOwinResponseMapper responseMapper,
IMappingMatcher mappingMatcher,
IGuidUtils guidUtils
) : base(next)
{ {
_options = Guard.NotNull(options); lock (_lock)
_requestMapper = Guard.NotNull(requestMapper);
_responseMapper = Guard.NotNull(responseMapper);
_mappingMatcher = Guard.NotNull(mappingMatcher);
_logEntryMapper = new LogEntryMapper(options);
_guidUtils = Guard.NotNull(guidUtils);
}
#else
public WireMockMiddleware(
Next next,
IWireMockMiddlewareOptions options,
IOwinRequestMapper requestMapper,
IOwinResponseMapper responseMapper,
IMappingMatcher mappingMatcher,
IGuidUtils guidUtils
)
{
_options = Guard.NotNull(options);
_requestMapper = Guard.NotNull(requestMapper);
_responseMapper = Guard.NotNull(responseMapper);
_mappingMatcher = Guard.NotNull(mappingMatcher);
_logEntryMapper = new LogEntryMapper(options);
_guidUtils = Guard.NotNull(guidUtils);
}
#endif
#if !USE_ASPNETCORE
public override Task Invoke(IContext ctx)
#else
public Task Invoke(IContext ctx)
#endif
{
if (_options.HandleRequestsSynchronously.GetValueOrDefault(false))
{ {
lock (_lock) return InvokeInternalAsync(ctx);
}
}
return InvokeInternalAsync(ctx);
}
private async Task InvokeInternalAsync(HttpContext ctx)
{
var request = await _requestMapper.MapAsync(ctx.Request, _options).ConfigureAwait(false);
var logRequest = false;
IResponseMessage? response = null;
(MappingMatcherResult? Match, MappingMatcherResult? Partial) result = (null, null);
try
{
foreach (var mapping in _options.Mappings.Values)
{
if (mapping.Scenario is null)
{ {
return InvokeInternalAsync(ctx); continue;
}
// Set scenario start
if (!_options.Scenarios.ContainsKey(mapping.Scenario) && mapping.IsStartState)
{
_options.Scenarios.TryAdd(mapping.Scenario, new ScenarioState
{
Name = mapping.Scenario
});
} }
} }
return InvokeInternalAsync(ctx); result = _mappingMatcher.FindBestMatch(request);
}
private async Task InvokeInternalAsync(IContext ctx) var targetMapping = result.Match?.Mapping;
{ if (targetMapping == null)
var request = await _requestMapper.MapAsync(ctx.Request, _options).ConfigureAwait(false);
var logRequest = false;
IResponseMessage? response = null;
(MappingMatcherResult? Match, MappingMatcherResult? Partial) result = (null, null);
try
{ {
foreach (var mapping in _options.Mappings.Values) logRequest = true;
_options.Logger.Warn("HttpStatusCode set to 404 : No matching mapping found");
response = ResponseMessageBuilder.Create(HttpStatusCode.NotFound, WireMockConstants.NoMatchingFound);
return;
}
logRequest = targetMapping.LogMapping;
if (targetMapping.IsAdminInterface && _options.AuthenticationMatcher != null && request.Headers != null)
{
var authorizationHeaderPresent = request.Headers.TryGetValue(HttpKnownHeaderNames.Authorization, out var authorization);
if (!authorizationHeaderPresent)
{ {
if (mapping.Scenario is null) _options.Logger.Error("HttpStatusCode set to 401, authorization header is missing.");
{ response = ResponseMessageBuilder.Create(HttpStatusCode.Unauthorized, null);
continue;
}
// Set scenario start
if (!_options.Scenarios.ContainsKey(mapping.Scenario) && mapping.IsStartState)
{
_options.Scenarios.TryAdd(mapping.Scenario, new ScenarioState
{
Name = mapping.Scenario
});
}
}
result = _mappingMatcher.FindBestMatch(request);
var targetMapping = result.Match?.Mapping;
if (targetMapping == null)
{
logRequest = true;
_options.Logger.Warn("HttpStatusCode set to 404 : No matching mapping found");
response = ResponseMessageBuilder.Create(HttpStatusCode.NotFound, WireMockConstants.NoMatchingFound);
return; return;
} }
logRequest = targetMapping.LogMapping; var authorizationHeaderMatchResult = _options.AuthenticationMatcher.IsMatch(authorization!.ToString());
if (!MatchScores.IsPerfect(authorizationHeaderMatchResult.Score))
if (targetMapping.IsAdminInterface && _options.AuthenticationMatcher != null && request.Headers != null)
{ {
var authorizationHeaderPresent = request.Headers.TryGetValue(HttpKnownHeaderNames.Authorization, out var authorization); _options.Logger.Error("HttpStatusCode set to 401, authentication failed.", authorizationHeaderMatchResult.Exception ?? throw new WireMockException("Authentication failed"));
if (!authorizationHeaderPresent) response = ResponseMessageBuilder.Create(HttpStatusCode.Unauthorized, null);
{ return;
_options.Logger.Error("HttpStatusCode set to 401, authorization header is missing."); }
response = ResponseMessageBuilder.Create(HttpStatusCode.Unauthorized, null); }
return;
}
var authorizationHeaderMatchResult = _options.AuthenticationMatcher.IsMatch(authorization!.ToString()); if (!targetMapping.IsAdminInterface && _options.RequestProcessingDelay > TimeSpan.Zero)
if (!MatchScores.IsPerfect(authorizationHeaderMatchResult.Score)) {
{ await Task.Delay(_options.RequestProcessingDelay.Value).ConfigureAwait(false);
_options.Logger.Error("HttpStatusCode set to 401, authentication failed.", authorizationHeaderMatchResult.Exception ?? throw new WireMockException("Authentication failed")); }
response = ResponseMessageBuilder.Create(HttpStatusCode.Unauthorized, null);
return; var (theResponse, theOptionalNewMapping) = await targetMapping.ProvideResponseAsync(request).ConfigureAwait(false);
} response = theResponse;
var responseBuilder = targetMapping.Provider as Response;
if (!targetMapping.IsAdminInterface && theOptionalNewMapping != null)
{
if (responseBuilder?.ProxyAndRecordSettings?.SaveMapping == true || targetMapping.Settings.ProxyAndRecordSettings?.SaveMapping == true)
{
_options.Mappings.TryAdd(theOptionalNewMapping.Guid, theOptionalNewMapping);
} }
if (!targetMapping.IsAdminInterface && _options.RequestProcessingDelay > TimeSpan.Zero) if (responseBuilder?.ProxyAndRecordSettings?.SaveMappingToFile == true || targetMapping.Settings.ProxyAndRecordSettings?.SaveMappingToFile == true)
{ {
await Task.Delay(_options.RequestProcessingDelay.Value).ConfigureAwait(false); var matcherMapper = new MatcherMapper(targetMapping.Settings);
var mappingConverter = new MappingConverter(matcherMapper);
var mappingToFileSaver = new MappingToFileSaver(targetMapping.Settings, mappingConverter);
mappingToFileSaver.SaveMappingToFile(theOptionalNewMapping);
} }
}
var (theResponse, theOptionalNewMapping) = await targetMapping.ProvideResponseAsync(request).ConfigureAwait(false); if (targetMapping.Scenario != null)
response = theResponse; {
UpdateScenarioState(targetMapping);
}
var responseBuilder = targetMapping.Provider as Response; if (!targetMapping.IsAdminInterface && targetMapping.Webhooks?.Length > 0)
{
await SendToWebhooksAsync(targetMapping, request, response).ConfigureAwait(false);
}
}
catch (Exception ex)
{
_options.Logger.Error($"Providing a Response for Mapping '{result.Match?.Mapping.Guid}' failed. HttpStatusCode set to 500. Exception: {ex}");
response = ResponseMessageBuilder.Create(500, ex.Message);
}
finally
{
var log = new LogEntry
{
Guid = _guidUtils.NewGuid(),
RequestMessage = request,
ResponseMessage = response,
if (!targetMapping.IsAdminInterface && theOptionalNewMapping != null) MappingGuid = result.Match?.Mapping?.Guid,
MappingTitle = result.Match?.Mapping?.Title,
RequestMatchResult = result.Match?.RequestMatchResult,
PartialMappingGuid = result.Partial?.Mapping?.Guid,
PartialMappingTitle = result.Partial?.Mapping?.Title,
PartialMatchResult = result.Partial?.RequestMatchResult
};
LogRequest(log, logRequest);
try
{
if (_options.SaveUnmatchedRequests == true && result.Match?.RequestMatchResult is not { IsPerfectMatch: true })
{ {
if (responseBuilder?.ProxyAndRecordSettings?.SaveMapping == true || targetMapping.Settings.ProxyAndRecordSettings?.SaveMapping == true) var filename = $"{log.Guid}.LogEntry.json";
{ _options.FileSystemHandler?.WriteUnmatchedRequest(filename, JsonUtils.Serialize(log));
_options.Mappings.TryAdd(theOptionalNewMapping.Guid, theOptionalNewMapping);
}
if (responseBuilder?.ProxyAndRecordSettings?.SaveMappingToFile == true || targetMapping.Settings.ProxyAndRecordSettings?.SaveMappingToFile == true)
{
var matcherMapper = new MatcherMapper(targetMapping.Settings);
var mappingConverter = new MappingConverter(matcherMapper);
var mappingToFileSaver = new MappingToFileSaver(targetMapping.Settings, mappingConverter);
mappingToFileSaver.SaveMappingToFile(theOptionalNewMapping);
}
} }
}
catch
{
// Empty catch
}
if (targetMapping.Scenario != null) try
{ {
UpdateScenarioState(targetMapping); await _responseMapper.MapAsync(response, ctx.Response).ConfigureAwait(false);
}
if (!targetMapping.IsAdminInterface && targetMapping.Webhooks?.Length > 0)
{
await SendToWebhooksAsync(targetMapping, request, response).ConfigureAwait(false);
}
} }
catch (Exception ex) catch (Exception ex)
{ {
_options.Logger.Error($"Providing a Response for Mapping '{result.Match?.Mapping.Guid}' failed. HttpStatusCode set to 500. Exception: {ex}"); _options.Logger.Error("HttpStatusCode set to 404 : No matching mapping found", ex);
response = ResponseMessageBuilder.Create(500, ex.Message);
var notFoundResponse = ResponseMessageBuilder.Create(HttpStatusCode.NotFound, WireMockConstants.NoMatchingFound);
await _responseMapper.MapAsync(notFoundResponse, ctx.Response).ConfigureAwait(false);
} }
finally }
await CompletedTask.ConfigureAwait(false);
}
private async Task SendToWebhooksAsync(IMapping mapping, IRequestMessage request, IResponseMessage response)
{
var tasks = new List<Func<Task>>();
for (int index = 0; index < mapping.Webhooks?.Length; index++)
{
var httpClientForWebhook = HttpClientBuilder.Build(mapping.Settings.WebhookSettings ?? new WebhookSettings());
var webhookSender = new WebhookSender(mapping.Settings);
var webhookRequest = mapping.Webhooks[index].Request;
var webHookIndex = index;
tasks.Add(async () =>
{ {
var log = new LogEntry
{
Guid = _guidUtils.NewGuid(),
RequestMessage = request,
ResponseMessage = response,
MappingGuid = result.Match?.Mapping?.Guid,
MappingTitle = result.Match?.Mapping?.Title,
RequestMatchResult = result.Match?.RequestMatchResult,
PartialMappingGuid = result.Partial?.Mapping?.Guid,
PartialMappingTitle = result.Partial?.Mapping?.Title,
PartialMatchResult = result.Partial?.RequestMatchResult
};
LogRequest(log, logRequest);
try try
{ {
if (_options.SaveUnmatchedRequests == true && result.Match?.RequestMatchResult is not { IsPerfectMatch: true }) var result = await webhookSender.SendAsync(httpClientForWebhook, mapping, webhookRequest, request, response).ConfigureAwait(false);
if (!result.IsSuccessStatusCode)
{ {
var filename = $"{log.Guid}.LogEntry.json"; var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
_options.FileSystemHandler?.WriteUnmatchedRequest(filename, JsonUtils.Serialize(log)); _options.Logger.Warn($"Sending message to Webhook [{webHookIndex}] from Mapping '{mapping.Guid}' failed. HttpStatusCode: {result.StatusCode} Content: {content}");
} }
} }
catch
{
// Empty catch
}
try
{
await _responseMapper.MapAsync(response, ctx.Response).ConfigureAwait(false);
}
catch (Exception ex) catch (Exception ex)
{ {
_options.Logger.Error("HttpStatusCode set to 404 : No matching mapping found", ex); _options.Logger.Error($"Sending message to Webhook [{webHookIndex}] from Mapping '{mapping.Guid}' failed. Exception: {ex}");
var notFoundResponse = ResponseMessageBuilder.Create(HttpStatusCode.NotFound, WireMockConstants.NoMatchingFound);
await _responseMapper.MapAsync(notFoundResponse, ctx.Response).ConfigureAwait(false);
} }
} });
await CompletedTask.ConfigureAwait(false);
} }
private async Task SendToWebhooksAsync(IMapping mapping, IRequestMessage request, IResponseMessage response) if (mapping.UseWebhooksFireAndForget == true)
{ {
var tasks = new List<Func<Task>>(); try
for (int index = 0; index < mapping.Webhooks?.Length; index++)
{ {
var httpClientForWebhook = HttpClientBuilder.Build(mapping.Settings.WebhookSettings ?? new WebhookSettings()); // Do not wait
var webhookSender = new WebhookSender(mapping.Settings); await Task.Run(() =>
var webhookRequest = mapping.Webhooks[index].Request;
var webHookIndex = index;
tasks.Add(async () =>
{ {
try Task.WhenAll(tasks.Select(async task => await task.Invoke())).ConfigureAwait(false);
{
var result = await webhookSender.SendAsync(httpClientForWebhook, mapping, webhookRequest, request, response).ConfigureAwait(false);
if (!result.IsSuccessStatusCode)
{
var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
_options.Logger.Warn($"Sending message to Webhook [{webHookIndex}] from Mapping '{mapping.Guid}' failed. HttpStatusCode: {result.StatusCode} Content: {content}");
}
}
catch (Exception ex)
{
_options.Logger.Error($"Sending message to Webhook [{webHookIndex}] from Mapping '{mapping.Guid}' failed. Exception: {ex}");
}
}); });
} }
if (mapping.UseWebhooksFireAndForget == true)
{
try
{
// Do not wait
await Task.Run(() =>
{
Task.WhenAll(tasks.Select(async task => await task.Invoke())).ConfigureAwait(false);
});
}
catch
{
// Ignore
}
}
else
{
await Task.WhenAll(tasks.Select(async task => await task.Invoke())).ConfigureAwait(false);
}
}
private void UpdateScenarioState(IMapping mapping)
{
var scenario = _options.Scenarios[mapping.Scenario!];
// Increase the number of times this state has been executed
scenario.Counter++;
// Only if the number of times this state is executed equals the required StateTimes, proceed to next state and reset the counter to 0
if (scenario.Counter == (mapping.TimesInSameState ?? 1))
{
scenario.NextState = mapping.NextState;
scenario.Counter = 0;
}
// Else just update Started and Finished
scenario.Started = true;
scenario.Finished = mapping.NextState == null;
}
private void LogRequest(LogEntry entry, bool addRequest)
{
_options.Logger.DebugRequestResponse(_logEntryMapper.Map(entry), entry.RequestMessage.Path.StartsWith("/__admin/"));
// If addRequest is set to true and MaxRequestLogCount is null or does have a value greater than 0, try to add a new request log.
if (addRequest && _options.MaxRequestLogCount is null or > 0)
{
TryAddLogEntry(entry);
}
// In case MaxRequestLogCount has a value greater than 0, try to delete existing request logs based on the count.
if (_options.MaxRequestLogCount is > 0)
{
var logEntries = _options.LogEntries.ToList();
foreach (var logEntry in logEntries.OrderBy(le => le.RequestMessage.DateTime).Take(logEntries.Count - _options.MaxRequestLogCount.Value))
{
TryRemoveLogEntry(logEntry);
}
}
// In case RequestLogExpirationDuration has a value greater than 0, try to delete existing request logs based on the date.
if (_options.RequestLogExpirationDuration is > 0)
{
var checkTime = DateTime.UtcNow.AddHours(-_options.RequestLogExpirationDuration.Value);
foreach (var logEntry in _options.LogEntries.ToList().Where(le => le.RequestMessage.DateTime < checkTime))
{
TryRemoveLogEntry(logEntry);
}
}
}
private void TryAddLogEntry(LogEntry logEntry)
{
try
{
_options.LogEntries.Add(logEntry);
}
catch catch
{ {
// Ignore exception (can happen during stress testing) // Ignore
}
}
else
{
await Task.WhenAll(tasks.Select(async task => await task.Invoke())).ConfigureAwait(false);
}
}
private void UpdateScenarioState(IMapping mapping)
{
var scenario = _options.Scenarios[mapping.Scenario!];
// Increase the number of times this state has been executed
scenario.Counter++;
// Only if the number of times this state is executed equals the required StateTimes, proceed to next state and reset the counter to 0
if (scenario.Counter == (mapping.TimesInSameState ?? 1))
{
scenario.NextState = mapping.NextState;
scenario.Counter = 0;
}
// Else just update Started and Finished
scenario.Started = true;
scenario.Finished = mapping.NextState == null;
}
private void LogRequest(LogEntry entry, bool addRequest)
{
_options.Logger.DebugRequestResponse(_logEntryMapper.Map(entry), entry.RequestMessage.Path.StartsWith("/__admin/"));
// If addRequest is set to true and MaxRequestLogCount is null or does have a value greater than 0, try to add a new request log.
if (addRequest && _options.MaxRequestLogCount is null or > 0)
{
TryAddLogEntry(entry);
}
// In case MaxRequestLogCount has a value greater than 0, try to delete existing request logs based on the count.
if (_options.MaxRequestLogCount is > 0)
{
var logEntries = _options.LogEntries.ToList();
foreach (var logEntry in logEntries.OrderBy(le => le.RequestMessage.DateTime).Take(logEntries.Count - _options.MaxRequestLogCount.Value))
{
TryRemoveLogEntry(logEntry);
} }
} }
private void TryRemoveLogEntry(LogEntry logEntry) // In case RequestLogExpirationDuration has a value greater than 0, try to delete existing request logs based on the date.
if (_options.RequestLogExpirationDuration is > 0)
{ {
try var checkTime = DateTime.UtcNow.AddHours(-_options.RequestLogExpirationDuration.Value);
foreach (var logEntry in _options.LogEntries.ToList().Where(le => le.RequestMessage.DateTime < checkTime))
{ {
_options.LogEntries.Remove(logEntry); TryRemoveLogEntry(logEntry);
}
catch
{
// Ignore exception (can happen during stress testing)
} }
} }
} }
private void TryAddLogEntry(LogEntry logEntry)
{
try
{
_options.LogEntries.Add(logEntry);
}
catch
{
// Ignore exception (can happen during stress testing)
}
}
private void TryRemoveLogEntry(LogEntry logEntry)
{
try
{
_options.LogEntries.Remove(logEntry);
}
catch
{
// Ignore exception (can happen during stress testing)
}
}
} }

View File

@@ -8,13 +8,17 @@ using WireMock.Matchers;
using WireMock.Types; using WireMock.Types;
using WireMock.Util; using WireMock.Util;
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
using Microsoft.AspNetCore.Builder;
#if !USE_ASPNETCORE using Microsoft.AspNetCore.Server.Kestrel.Https;
using Owin;
#else
using IAppBuilder = Microsoft.AspNetCore.Builder.IApplicationBuilder;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
#endif using ClientCertificateMode = Microsoft.AspNetCore.Server.Kestrel.Https.ClientCertificateMode;
//#if !USE_ASPNETCORE
//using Owin;
//#else
//using IAppBuilder = Microsoft.AspNetCore.Builder.IApplicationBuilder;
//using Microsoft.Extensions.DependencyInjection;
//#endif
namespace WireMock.Owin; namespace WireMock.Owin;
@@ -38,11 +42,11 @@ internal class WireMockMiddlewareOptions : IWireMockMiddlewareOptions
public int? MaxRequestLogCount { get; set; } public int? MaxRequestLogCount { get; set; }
public Action<IAppBuilder>? PreWireMockMiddlewareInit { get; set; } public Action<IApplicationBuilder>? PreWireMockMiddlewareInit { get; set; }
public Action<IAppBuilder>? PostWireMockMiddlewareInit { get; set; } public Action<IApplicationBuilder>? PostWireMockMiddlewareInit { get; set; }
#if USE_ASPNETCORE //#if USE_ASPNETCORE
public Action<IServiceCollection>? AdditionalServiceRegistration { get; set; } public Action<IServiceCollection>? AdditionalServiceRegistration { get; set; }
public CorsPolicyOptions? CorsPolicyOptions { get; set; } public CorsPolicyOptions? CorsPolicyOptions { get; set; }
@@ -51,7 +55,7 @@ internal class WireMockMiddlewareOptions : IWireMockMiddlewareOptions
/// <inheritdoc /> /// <inheritdoc />
public bool AcceptAnyClientCertificate { get; set; } public bool AcceptAnyClientCertificate { get; set; }
#endif //#endif
/// <inheritdoc cref="IWireMockMiddlewareOptions.FileSystemHandler"/> /// <inheritdoc cref="IWireMockMiddlewareOptions.FileSystemHandler"/>
public IFileSystemHandler? FileSystemHandler { get; set; } public IFileSystemHandler? FileSystemHandler { get; set; }

View File

@@ -6,9 +6,10 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Net; using System.Net;
#if USE_ASPNETCORE
using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.X509Certificates;
#endif //#if USE_ASPNETCORE
//using System.Security.Cryptography.X509Certificates;
//#endif
using Stef.Validation; using Stef.Validation;
using WireMock.Models; using WireMock.Models;
using WireMock.Owin; using WireMock.Owin;
@@ -82,11 +83,11 @@ public class RequestMessage : IRequestMessage
/// <inheritdoc /> /// <inheritdoc />
public byte[]? BodyAsBytes { get; } public byte[]? BodyAsBytes { get; }
#if MIMEKIT //#if MIMEKIT
/// <inheritdoc /> /// <inheritdoc />
[Newtonsoft.Json.JsonIgnore] // Issue 1001 [Newtonsoft.Json.JsonIgnore] // Issue 1001
public Models.Mime.IMimeMessageData? BodyAsMimeMessage { get; } public Models.Mime.IMimeMessageData? BodyAsMimeMessage { get; }
#endif //#endif
/// <inheritdoc /> /// <inheritdoc />
public string? DetectedBodyType { get; } public string? DetectedBodyType { get; }
@@ -109,10 +110,10 @@ public class RequestMessage : IRequestMessage
/// <inheritdoc /> /// <inheritdoc />
public string Origin { get; } public string Origin { get; }
#if USE_ASPNETCORE //#if USE_ASPNETCORE
/// <inheritdoc /> /// <inheritdoc />
public X509Certificate2? ClientCertificate { get; } public X509Certificate2? ClientCertificate { get; }
#endif //#endif
/// <summary> /// <summary>
/// Used for Unit Testing /// Used for Unit Testing
@@ -136,9 +137,9 @@ public class RequestMessage : IRequestMessage
IDictionary<string, string[]>? headers = null, IDictionary<string, string[]>? headers = null,
IDictionary<string, string>? cookies = null, IDictionary<string, string>? cookies = null,
string httpVersion = "1.1" string httpVersion = "1.1"
#if USE_ASPNETCORE //#if USE_ASPNETCORE
, X509Certificate2? clientCertificate = null , X509Certificate2? clientCertificate = null
#endif //#endif
) )
{ {
Guard.NotNull(urlDetails); Guard.NotNull(urlDetails);
@@ -178,9 +179,9 @@ public class RequestMessage : IRequestMessage
Query = QueryStringParser.Parse(RawQuery, options?.QueryParameterMultipleValueSupport); Query = QueryStringParser.Parse(RawQuery, options?.QueryParameterMultipleValueSupport);
QueryIgnoreCase = new Dictionary<string, WireMockList<string>>(Query, StringComparer.OrdinalIgnoreCase); QueryIgnoreCase = new Dictionary<string, WireMockList<string>>(Query, StringComparer.OrdinalIgnoreCase);
#if USE_ASPNETCORE //#if USE_ASPNETCORE
ClientCertificate = clientCertificate; ClientCertificate = clientCertificate;
#endif //#endif
#if MIMEKIT #if MIMEKIT
try try
@@ -206,7 +207,6 @@ public class RequestMessage : IRequestMessage
} }
var query = !ignoreCase ? Query : new Dictionary<string, WireMockList<string>>(Query, StringComparer.OrdinalIgnoreCase); var query = !ignoreCase ? Query : new Dictionary<string, WireMockList<string>>(Query, StringComparer.OrdinalIgnoreCase);
return query.TryGetValue(key, out var value) ? value : null;
return query.ContainsKey(key) ? query[key] : null;
} }
} }

View File

@@ -295,11 +295,11 @@ public partial class WireMockServer
WatchStaticMappings = _settings.WatchStaticMappings, WatchStaticMappings = _settings.WatchStaticMappings,
WatchStaticMappingsInSubdirectories = _settings.WatchStaticMappingsInSubdirectories, WatchStaticMappingsInSubdirectories = _settings.WatchStaticMappingsInSubdirectories,
#if USE_ASPNETCORE //#if USE_ASPNETCORE
AcceptAnyClientCertificate = _settings.AcceptAnyClientCertificate, AcceptAnyClientCertificate = _settings.AcceptAnyClientCertificate,
ClientCertificateMode = _settings.ClientCertificateMode, ClientCertificateMode = _settings.ClientCertificateMode,
CorsPolicyOptions = _settings.CorsPolicyOptions?.ToString() CorsPolicyOptions = _settings.CorsPolicyOptions?.ToString()
#endif //#endif
}; };
model.ProxyAndRecordSettings = TinyMapperUtils.Instance.Map(_settings.ProxyAndRecordSettings); model.ProxyAndRecordSettings = TinyMapperUtils.Instance.Map(_settings.ProxyAndRecordSettings);
@@ -333,12 +333,12 @@ public partial class WireMockServer
InitSettings(_settings); InitSettings(_settings);
#if USE_ASPNETCORE //#if USE_ASPNETCORE
if (Enum.TryParse<CorsPolicyOptions>(settings.CorsPolicyOptions, true, out var corsPolicyOptions)) if (Enum.TryParse<CorsPolicyOptions>(settings.CorsPolicyOptions, true, out var corsPolicyOptions))
{ {
_settings.CorsPolicyOptions = corsPolicyOptions; _settings.CorsPolicyOptions = corsPolicyOptions;
} }
#endif //#endif
WireMockMiddlewareOptionsHelper.InitFromSettings(_settings, _options, o => WireMockMiddlewareOptionsHelper.InitFromSettings(_settings, _options, o =>
{ {
@@ -347,11 +347,11 @@ public partial class WireMockServer
o.RequestProcessingDelay = TimeSpan.FromMilliseconds(settings.GlobalProcessingDelay.Value); o.RequestProcessingDelay = TimeSpan.FromMilliseconds(settings.GlobalProcessingDelay.Value);
} }
#if USE_ASPNETCORE //#if USE_ASPNETCORE
o.CorsPolicyOptions = corsPolicyOptions; o.CorsPolicyOptions = corsPolicyOptions;
o.ClientCertificateMode = _settings.ClientCertificateMode; o.ClientCertificateMode = (Microsoft.AspNetCore.Server.Kestrel.Https.ClientCertificateMode) _settings.ClientCertificateMode;
o.AcceptAnyClientCertificate = _settings.AcceptAnyClientCertificate; o.AcceptAnyClientCertificate = _settings.AcceptAnyClientCertificate;
#endif //#endif
}); });
return ResponseMessageBuilder.Create(200, "Settings updated"); return ResponseMessageBuilder.Create(200, "Settings updated");
@@ -900,6 +900,6 @@ public partial class WireMockServer
} }
var singleResult = ((JObject)value).ToObject<T>(); var singleResult = ((JObject)value).ToObject<T>();
return new[] { singleResult! }; return [singleResult!];
} }
} }

View File

@@ -62,7 +62,7 @@ public partial class WireMockServer : IWireMockServer
/// <inheritdoc /> /// <inheritdoc />
[PublicAPI] [PublicAPI]
public int Port => Ports?.FirstOrDefault() ?? default; public int Port => Ports?.FirstOrDefault() ?? 0;
/// <inheritdoc /> /// <inheritdoc />
[PublicAPI] [PublicAPI]
@@ -411,16 +411,16 @@ public partial class WireMockServer : IWireMockServer
_dateTimeUtils _dateTimeUtils
); );
#if USE_ASPNETCORE //#if USE_ASPNETCORE
_options.AdditionalServiceRegistration = _settings.AdditionalServiceRegistration; _options.AdditionalServiceRegistration = _settings.AdditionalServiceRegistration;
_options.CorsPolicyOptions = _settings.CorsPolicyOptions; _options.CorsPolicyOptions = _settings.CorsPolicyOptions;
_options.ClientCertificateMode = _settings.ClientCertificateMode; _options.ClientCertificateMode = (Microsoft.AspNetCore.Server.Kestrel.Https.ClientCertificateMode)_settings.ClientCertificateMode;
_options.AcceptAnyClientCertificate = _settings.AcceptAnyClientCertificate; _options.AcceptAnyClientCertificate = _settings.AcceptAnyClientCertificate;
_httpServer = new AspNetCoreSelfHost(_options, urlOptions); _httpServer = new AspNetCoreSelfHost(_options, urlOptions);
#else //#else
_httpServer = new OwinSelfHost(_options, urlOptions); // _httpServer = new OwinSelfHost(_options, urlOptions);
#endif //#endif
var startTask = _httpServer.StartAsync(); var startTask = _httpServer.StartAsync();
using (var ctsStartTimeout = new CancellationTokenSource(settings.StartTimeout)) using (var ctsStartTimeout = new CancellationTokenSource(settings.StartTimeout))

View File

@@ -1,13 +1,14 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
using System; using System;
using Microsoft.AspNetCore.Http;
using WireMock.Models; using WireMock.Models;
using Stef.Validation; using Stef.Validation;
#if !USE_ASPNETCORE //#if !USE_ASPNETCORE
using Microsoft.Owin; //using Microsoft.Owin;
#else //#else
using Microsoft.AspNetCore.Http; //using Microsoft.AspNetCore.Http;
#endif //#endif
namespace WireMock.Util; namespace WireMock.Util;

View File

@@ -3,7 +3,8 @@
<Description>Minimal version from the lightweight Http Mocking Server for .NET</Description> <Description>Minimal version from the lightweight Http Mocking Server for .NET</Description>
<AssemblyTitle>WireMock.Net.Minimal</AssemblyTitle> <AssemblyTitle>WireMock.Net.Minimal</AssemblyTitle>
<Authors>Stef Heyenrath</Authors> <Authors>Stef Heyenrath</Authors>
<TargetFrameworks>net451;net452;net46;net461;netstandard1.3;netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0</TargetFrameworks> <!--<TargetFrameworks>net451;net452;net46;net461;netstandard1.3;netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0</TargetFrameworks>-->
<TargetFrameworks>net48;net8.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<AssemblyName>WireMock.Net.Minimal</AssemblyName> <AssemblyName>WireMock.Net.Minimal</AssemblyName>
<PackageId>WireMock.Net.Minimal</PackageId> <PackageId>WireMock.Net.Minimal</PackageId>
@@ -28,7 +29,7 @@
<CodeAnalysisRuleSet>../WireMock.Net/WireMock.Net.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>../WireMock.Net/WireMock.Net.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'netstandard1.3' or '$(TargetFramework)' == 'netstandard2.0' or '$(TargetFramework)' == 'netstandard2.1'"> <!--<PropertyGroup Condition="'$(TargetFramework)' == 'netstandard1.3' or '$(TargetFramework)' == 'netstandard2.0' or '$(TargetFramework)' == 'netstandard2.1'">
<DefineConstants>$(DefineConstants);NETSTANDARD;USE_ASPNETCORE</DefineConstants> <DefineConstants>$(DefineConstants);NETSTANDARD;USE_ASPNETCORE</DefineConstants>
</PropertyGroup> </PropertyGroup>
@@ -46,9 +47,9 @@
<PropertyGroup Condition="'$(TargetFramework)' != 'netstandard1.3' and '$(TargetFramework)' != 'net451' and '$(TargetFramework)' != 'net452' and '$(TargetFramework)' != 'net46' and '$(TargetFramework)' != 'net461'"> <PropertyGroup Condition="'$(TargetFramework)' != 'netstandard1.3' and '$(TargetFramework)' != 'net451' and '$(TargetFramework)' != 'net452' and '$(TargetFramework)' != 'net46' and '$(TargetFramework)' != 'net461'">
<DefineConstants>$(DefineConstants);GRAPHQL;MIMEKIT;PROTOBUF</DefineConstants> <DefineConstants>$(DefineConstants);GRAPHQL;MIMEKIT;PROTOBUF</DefineConstants>
</PropertyGroup> </PropertyGroup>-->
<PropertyGroup Condition="'$(TargetFramework)' != 'netstandard1.3' and '$(TargetFramework)' != 'net451' and '$(TargetFramework)' != 'net452' and '$(TargetFramework)' != 'net46' "> <PropertyGroup Condition="'$(TargetFramework)' == 'net8.0' ">
<DefineConstants>$(DefineConstants);TRAILINGHEADERS</DefineConstants> <DefineConstants>$(DefineConstants);TRAILINGHEADERS</DefineConstants>
</PropertyGroup> </PropertyGroup>
@@ -57,34 +58,55 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="JsonConverter.Abstractions" Version="0.7.0" /> <!--<PackageReference Include="JsonConverter.Abstractions" Version="0.7.0" />-->
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <!--<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />-->
<PackageReference Include="NJsonSchema.Extensions" Version="0.1.0" /> <PackageReference Include="NJsonSchema.Extensions" Version="0.1.0" />
<PackageReference Include="NSwag.Core" Version="13.16.1" /> <PackageReference Include="NSwag.Core" Version="13.16.1" />
<PackageReference Include="SimMetrics.Net" Version="1.0.5" /> <PackageReference Include="SimMetrics.Net" Version="1.0.5" />
<PackageReference Include="JmesPath.Net" Version="1.0.330" /> <PackageReference Include="JmesPath.Net" Version="1.0.330" />
<PackageReference Include="AnyOf" Version="0.4.0" /> <!--<PackageReference Include="AnyOf" Version="0.4.0" />-->
<PackageReference Include="TinyMapper.Signed" Version="4.0.0" /> <PackageReference Include="TinyMapper.Signed" Version="4.0.0" />
<PackageReference Include="Nullable" Version="1.3.1"> <PackageReference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="6.34.0" />
<!--<PackageReference Include="Nullable" Version="1.3.1">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>-->
<PackageReference Include="Scriban.Signed" Version="5.5.0" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' != 'netstandard1.3' "> <ItemGroup Condition=" '$(TargetFramework)' == 'net8.0'">
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net48'">
<!--<PackageReference Include="Polyfill" Version="8.8.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>-->
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.3.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
</ItemGroup>
<!--<ItemGroup Condition=" '$(TargetFramework)' != 'netstandard1.3' ">
<PackageReference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="6.34.0" /> <PackageReference Include="Microsoft.IdentityModel.Protocols.OpenIdConnect" Version="6.34.0" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net451' or '$(TargetFramework)' == 'net452' "> <ItemGroup Condition=" '$(TargetFramework)' == 'net451' or '$(TargetFramework)' == 'net452' ">
<!-- Required for WebRequestHandler --> --><!-- Required for WebRequestHandler --><!--
<Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Net.Http.WebRequest" />
<PackageReference Include="Microsoft.AspNet.WebApi.OwinSelfHost" Version="5.2.6" /> <PackageReference Include="Microsoft.AspNet.WebApi.OwinSelfHost" Version="5.2.6" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" /> <PackageReference Include="System.ValueTuple" Version="4.5.0" />
<PackageReference Include="Scriban.Signed" Version="2.1.4" /> <PackageReference Include="Scriban.Signed" Version="2.1.4" />
</ItemGroup> </ItemGroup>-->
<ItemGroup Condition=" '$(TargetFramework)' == 'net46' "> <!--<ItemGroup Condition=" '$(TargetFramework)' == 'net46' ">
<PackageReference Include="Microsoft.AspNet.WebApi.OwinSelfHost" Version="5.2.6" /> <PackageReference Include="Microsoft.AspNet.WebApi.OwinSelfHost" Version="5.2.6" />
<PackageReference Include="Microsoft.Owin" Version="4.2.2" /> <PackageReference Include="Microsoft.Owin" Version="4.2.2" />
<PackageReference Include="Microsoft.Owin.Host.HttpListener" Version="4.0.0" /> <PackageReference Include="Microsoft.Owin.Host.HttpListener" Version="4.0.0" />
@@ -92,17 +114,17 @@
<PackageReference Include="System.Net.Http" Version="4.3.4" /> <PackageReference Include="System.Net.Http" Version="4.3.4" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" /> <PackageReference Include="System.ValueTuple" Version="4.5.0" />
<PackageReference Include="Scriban.Signed" Version="2.1.4" /> <PackageReference Include="Scriban.Signed" Version="2.1.4" />
</ItemGroup> </ItemGroup>-->
<ItemGroup Condition=" '$(TargetFramework)' == 'net461' "> <!--<ItemGroup Condition=" '$(TargetFramework)' == 'net461' ">
<PackageReference Include="Scriban.Signed" Version="2.1.4" /> <PackageReference Include="Scriban.Signed" Version="2.1.4" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
<!-- https://github.com/wiremock/WireMock.Net/issues/507 --> --><!-- https://github.com/wiremock/WireMock.Net/issues/507 --><!--
<PackageReference Include="Microsoft.AspNetCore.Server.IIS" Version="2.2.6" /> <PackageReference Include="Microsoft.AspNetCore.Server.IIS" Version="2.2.6" />
</ItemGroup> </ItemGroup>-->
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard1.3' "> <!--<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard1.3' ">
<PackageReference Include="System.Collections.Specialized" Version="4.3.0" /> <PackageReference Include="System.Collections.Specialized" Version="4.3.0" />
<PackageReference Include="Microsoft.AspNetCore" Version="1.1.7" /> <PackageReference Include="Microsoft.AspNetCore" Version="1.1.7" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Https" Version="1.1.3" /> <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Https" Version="1.1.3" />
@@ -110,24 +132,24 @@
<PackageReference Include="System.Xml.XPath.XmlDocument" Version="4.3.0" /> <PackageReference Include="System.Xml.XPath.XmlDocument" Version="4.3.0" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" /> <PackageReference Include="System.ValueTuple" Version="4.5.0" />
<PackageReference Include="Scriban.Signed" Version="2.1.4" /> <PackageReference Include="Scriban.Signed" Version="2.1.4" />
</ItemGroup> </ItemGroup>-->
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' or '$(TargetFramework)' == 'netstandard2.1' "> <!--<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' or '$(TargetFramework)' == 'netstandard2.1' ">
<PackageReference Include="Scriban.Signed" Version="5.5.0" /> <PackageReference Include="Scriban.Signed" Version="5.5.0" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
<!-- https://github.com/wiremock/WireMock.Net/issues/507 --> --><!-- https://github.com/wiremock/WireMock.Net/issues/507 --><!--
<PackageReference Include="Microsoft.AspNetCore.Server.IIS" Version="2.2.6" /> <PackageReference Include="Microsoft.AspNetCore.Server.IIS" Version="2.2.6" />
</ItemGroup> </ItemGroup>-->
<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp3.1' or '$(TargetFramework)' == 'net5.0' or '$(TargetFramework)' == 'net6.0' or '$(TargetFramework)' == 'net7.0' or '$(TargetFramework)' == 'net8.0'"> <!--<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp3.1' or '$(TargetFramework)' == 'net5.0' or '$(TargetFramework)' == 'net6.0' or '$(TargetFramework)' == 'net7.0' or '$(TargetFramework)' == 'net8.0'">
<FrameworkReference Include="Microsoft.AspNetCore.App" /> <FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Scriban.Signed" Version="5.5.0" /> <PackageReference Include="Scriban.Signed" Version="5.5.0" />
</ItemGroup> </ItemGroup>-->
<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp3.1' "> <!--<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp3.1' ">
<PackageReference Include="System.ComponentModel" Version="4.3.0" /> <PackageReference Include="System.ComponentModel" Version="4.3.0" />
</ItemGroup> </ItemGroup>-->
<ItemGroup> <ItemGroup>
<Compile Update="Server\WireMockServer.*.cs"> <Compile Update="Server\WireMockServer.*.cs">
@@ -147,9 +169,9 @@
</Compile> </Compile>
</ItemGroup> </ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' != 'netstandard1.3' and '$(TargetFramework)' != 'net451' and '$(TargetFramework)' != 'net452' "> <!--<ItemGroup Condition="'$(TargetFramework)' != 'netstandard1.3' and '$(TargetFramework)' != 'net451' and '$(TargetFramework)' != 'net452' ">
<PackageReference Include="Handlebars.Net.Helpers.Xslt" Version="2.5.2" /> <PackageReference Include="Handlebars.Net.Helpers.Xslt" Version="2.5.2" />
</ItemGroup> </ItemGroup>-->
<!--<ItemGroup> <!--<ItemGroup>
--><!-- CVE-2021-26701 and https://github.com/wiremock/WireMock.Net/issues/697 --><!-- --><!-- CVE-2021-26701 and https://github.com/wiremock/WireMock.Net/issues/697 --><!--
@@ -159,9 +181,10 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\WireMock.Net.Shared\WireMock.Net.Shared.csproj" /> <ProjectReference Include="..\WireMock.Net.Shared\WireMock.Net.Shared.csproj" />
<ProjectReference Include="..\WireMock.Org.Abstractions\WireMock.Org.Abstractions.csproj" /> <ProjectReference Include="..\WireMock.Org.Abstractions\WireMock.Org.Abstractions.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' != 'netstandard1.3' and '$(TargetFramework)' != 'net451' and '$(TargetFramework)' != 'net452' and '$(TargetFramework)' != 'net46'">
<ProjectReference Include="..\WireMock.Net.OpenApiParser\WireMock.Net.OpenApiParser.csproj" /> <ProjectReference Include="..\WireMock.Net.OpenApiParser\WireMock.Net.OpenApiParser.csproj" />
</ItemGroup> </ItemGroup>
<!--<ItemGroup Condition="'$(TargetFramework)' != 'netstandard1.3' and '$(TargetFramework)' != 'net451' and '$(TargetFramework)' != 'net452' and '$(TargetFramework)' != 'net46'">
<ProjectReference Include="..\WireMock.Net.OpenApiParser\WireMock.Net.OpenApiParser.csproj" />
</ItemGroup>-->
</Project> </Project>

View File

@@ -5,9 +5,7 @@ using System.Linq;
using System.Reflection; using System.Reflection;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Nodes; using System.Text.Json.Nodes;
using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Models.Interfaces;
using WireMock.Net.OpenApiParser.Types; using WireMock.Net.OpenApiParser.Types;
namespace WireMock.Net.OpenApiParser.Extensions; namespace WireMock.Net.OpenApiParser.Extensions;

View File

@@ -6,8 +6,7 @@ using System.Diagnostics.CodeAnalysis;
using System.Linq; using System.Linq;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Nodes; using System.Text.Json.Nodes;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi;
using Microsoft.OpenApi.Models.Interfaces;
using Newtonsoft.Json; using Newtonsoft.Json;
using Stef.Validation; using Stef.Validation;
using WireMock.Admin.Mappings; using WireMock.Admin.Mappings;

View File

@@ -1,7 +1,7 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
using System; using System;
using Microsoft.OpenApi.Models.Interfaces; using Microsoft.OpenApi;
namespace WireMock.Net.OpenApiParser.Settings; namespace WireMock.Net.OpenApiParser.Settings;

View File

@@ -1,7 +1,7 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
using System; using System;
using Microsoft.OpenApi.Models.Interfaces; using Microsoft.OpenApi;
using RandomDataGenerator.FieldOptions; using RandomDataGenerator.FieldOptions;
using RandomDataGenerator.Randomizers; using RandomDataGenerator.Randomizers;

View File

@@ -1,8 +1,7 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
using System; using System;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi;
using Microsoft.OpenApi.Models.Interfaces;
namespace WireMock.Net.OpenApiParser.Settings; namespace WireMock.Net.OpenApiParser.Settings;

View File

@@ -3,8 +3,7 @@
using System; using System;
using System.Linq; using System.Linq;
using System.Text.Json.Nodes; using System.Text.Json.Nodes;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi;
using Microsoft.OpenApi.Models.Interfaces;
using Stef.Validation; using Stef.Validation;
using WireMock.Net.OpenApiParser.Extensions; using WireMock.Net.OpenApiParser.Extensions;
using WireMock.Net.OpenApiParser.Settings; using WireMock.Net.OpenApiParser.Settings;

View File

@@ -2,7 +2,8 @@
<PropertyGroup> <PropertyGroup>
<Description>An OpenApi (swagger) parser to generate MappingModel or mapping.json file.</Description> <Description>An OpenApi (swagger) parser to generate MappingModel or mapping.json file.</Description>
<TargetFrameworks>netstandard2.0;net8.0</TargetFrameworks> <!--<TargetFrameworks>netstandard2.0;net8.0</TargetFrameworks>-->
<TargetFrameworks>net48;net8.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageTags>wiremock;openapi;OAS;raml;converter;parser;openapiparser</PackageTags> <PackageTags>wiremock;openapi;OAS;raml;converter;parser;openapiparser</PackageTags>
<ProjectGuid>{E5B03EEF-822C-4295-952B-4479AD30082B}</ProjectGuid> <ProjectGuid>{E5B03EEF-822C-4295-952B-4479AD30082B}</ProjectGuid>
@@ -23,18 +24,18 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="PolySharp" Version="1.15.0"> <PackageReference Include="Polyfill" Version="8.8.0">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="RamlToOpenApiConverter.SourceOnly" Version="0.8.0" /> <PackageReference Include="RamlToOpenApiConverter.SourceOnly" Version="0.9.0" />
<PackageReference Include="YamlDotNet" Version="8.1.0" /> <PackageReference Include="YamlDotNet" Version="16.3.0" />
<PackageReference Include="RandomDataGenerator.Net" Version="1.0.19" /> <PackageReference Include="RandomDataGenerator.Net" Version="1.0.19.1" />
<PackageReference Include="Stef.Validation" Version="0.1.1" /> <PackageReference Include="Stef.Validation" Version="0.2.0" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition="'$(Configuration)' == 'Debug'"> <ItemGroup Condition="'$(Configuration)' == 'Debug'">
<PackageReference Include="Microsoft.OpenApi.YamlReader" Version="2.0.0-preview.17" /> <PackageReference Include="Microsoft.OpenApi.YamlReader" Version="2.3.0" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition="'$(Configuration)' == 'Release'"> <ItemGroup Condition="'$(Configuration)' == 'Release'">

View File

@@ -5,7 +5,7 @@ using System.Collections.Generic;
using System.IO; using System.IO;
using System.Text; using System.Text;
using JetBrains.Annotations; using JetBrains.Annotations;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi;
using Microsoft.OpenApi.Reader; using Microsoft.OpenApi.Reader;
using Microsoft.OpenApi.YamlReader; using Microsoft.OpenApi.YamlReader;
using RamlToOpenApiConverter; using RamlToOpenApiConverter;

View File

@@ -40,7 +40,7 @@ internal static class ProtoDefinitionDataHelper
// Build comment and get content from file. // Build comment and get content from file.
var comment = $"// {protoRelativePath}"; var comment = $"// {protoRelativePath}";
#if NETSTANDARD2_0 || NET462 #if NETSTANDARD2_0 || NET462 || NET48
var content = File.ReadAllText(filePath); var content = File.ReadAllText(filePath);
#else #else
var content = await File.ReadAllTextAsync(filePath, cancellationToken); var content = await File.ReadAllTextAsync(filePath, cancellationToken);

View File

@@ -4,7 +4,8 @@
<Description>ProtoBuf and gRPC support for WireMock.Net</Description> <Description>ProtoBuf and gRPC support for WireMock.Net</Description>
<AssemblyTitle>WireMock.Net.ProtoBuf</AssemblyTitle> <AssemblyTitle>WireMock.Net.ProtoBuf</AssemblyTitle>
<Authors>Stef Heyenrath</Authors> <Authors>Stef Heyenrath</Authors>
<TargetFrameworks>netstandard2.1;net462;net6.0;net8.0</TargetFrameworks> <!--<TargetFrameworks>netstandard2.1;net462;net6.0;net8.0</TargetFrameworks>-->
<TargetFrameworks>net48;net8.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageTags>wiremock;matchers;matcher;protobuf;grpc</PackageTags> <PackageTags>wiremock;matchers;matcher;protobuf;grpc</PackageTags>
<RootNamespace>WireMock</RootNamespace> <RootNamespace>WireMock</RootNamespace>
@@ -26,7 +27,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="ProtoBufJsonConverter" Version="0.10.0" /> <PackageReference Include="ProtoBufJsonConverter" Version="0.10.0.1" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -328,7 +328,7 @@ public interface IWireMockAdminApi
/// <param name="protoDefinition">The ProtoDefinition as text.</param> /// <param name="protoDefinition">The ProtoDefinition as text.</param>
/// <param name="cancellationToken">The optional cancellationToken.</param> /// <param name="cancellationToken">The optional cancellationToken.</param>
[Post("protodefinitions/{id}")] [Post("protodefinitions/{id}")]
Task<StatusModel> AddProtoDefinitionAsync([Path] string id, [Body] string body, CancellationToken cancellationToken = default); Task<StatusModel> AddProtoDefinitionAsync([Path] string id, [Body] string protoDefinition, CancellationToken cancellationToken = default);
/// <summary> /// <summary>
/// Check if a file exists /// Check if a file exists

View File

@@ -4,7 +4,8 @@
<Description>A RestClient using RestEase to access the admin interface.</Description> <Description>A RestClient using RestEase to access the admin interface.</Description>
<AssemblyTitle>WireMock.Net.RestClient</AssemblyTitle> <AssemblyTitle>WireMock.Net.RestClient</AssemblyTitle>
<Authors>Stef Heyenrath</Authors> <Authors>Stef Heyenrath</Authors>
<TargetFrameworks>net45;netstandard1.3;netstandard2.0;netstandard2.1</TargetFrameworks> <!--<TargetFrameworks>net45;netstandard1.3;netstandard2.0;netstandard2.1</TargetFrameworks>-->
<TargetFrameworks>net48;net8.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<AssemblyName>WireMock.Net.RestClient</AssemblyName> <AssemblyName>WireMock.Net.RestClient</AssemblyName>
<PackageId>WireMock.Net.RestClient</PackageId> <PackageId>WireMock.Net.RestClient</PackageId>
@@ -33,9 +34,9 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="JsonConverter.Newtonsoft.Json" Version="0.7.0" /> <PackageReference Include="JsonConverter.Newtonsoft.Json" Version="0.7.2" />
<PackageReference Include="RestEase" Version="1.6.4" /> <PackageReference Include="RestEase" Version="1.6.4" />
<PackageReference Include="Stef.Validation" Version="0.1.1" /> <PackageReference Include="Stef.Validation" Version="0.2.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -147,7 +147,7 @@ public interface IMapping
/// ProvideResponseAsync /// ProvideResponseAsync
/// </summary> /// </summary>
/// <param name="requestMessage">The request message.</param> /// <param name="requestMessage">The request message.</param>
/// <returns>The <see cref="ResponseMessage"/> including a new (optional) <see cref="IMapping"/>.</returns> /// <returns>The <see cref="IResponseMessage"/> including a new (optional) <see cref="IMapping"/>.</returns>
Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IRequestMessage requestMessage); Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IRequestMessage requestMessage);
/// <summary> /// <summary>

View File

@@ -14,10 +14,7 @@ using WireMock.RegularExpressions;
using WireMock.Types; using WireMock.Types;
using System.Globalization; using System.Globalization;
using WireMock.Models; using WireMock.Models;
#if USE_ASPNETCORE
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
#endif
namespace WireMock.Settings; namespace WireMock.Settings;
@@ -151,7 +148,7 @@ public class WireMockServerSettings
[JsonIgnore] [JsonIgnore]
public Action<object>? PostWireMockMiddlewareInit { get; set; } public Action<object>? PostWireMockMiddlewareInit { get; set; }
#if USE_ASPNETCORE //#if USE_ASPNETCORE
/// <summary> /// <summary>
/// Action which is called with IServiceCollection when ASP.NET Core DI is being configured. [Optional] /// Action which is called with IServiceCollection when ASP.NET Core DI is being configured. [Optional]
/// </summary> /// </summary>
@@ -164,7 +161,7 @@ public class WireMockServerSettings
/// </summary> /// </summary>
[PublicAPI] [PublicAPI]
public CorsPolicyOptions? CorsPolicyOptions { get; set; } public CorsPolicyOptions? CorsPolicyOptions { get; set; }
#endif //#endif
/// <summary> /// <summary>
/// The IWireMockLogger which logs Debug, Info, Warning or Error /// The IWireMockLogger which logs Debug, Info, Warning or Error
@@ -249,7 +246,7 @@ public class WireMockServerSettings
[PublicAPI] [PublicAPI]
public bool CustomCertificateDefined => CertificateSettings?.IsDefined == true; public bool CustomCertificateDefined => CertificateSettings?.IsDefined == true;
#if USE_ASPNETCORE //#if USE_ASPNETCORE
/// <summary> /// <summary>
/// Client certificate mode for the server /// Client certificate mode for the server
/// </summary> /// </summary>
@@ -260,7 +257,7 @@ public class WireMockServerSettings
/// Whether to accept any client certificate /// Whether to accept any client certificate
/// </summary> /// </summary>
public bool AcceptAnyClientCertificate { get; set; } public bool AcceptAnyClientCertificate { get; set; }
#endif //#endif
/// <summary> /// <summary>
/// Defines the global IWebhookSettings to use. /// Defines the global IWebhookSettings to use.

View File

@@ -2,7 +2,8 @@
<PropertyGroup> <PropertyGroup>
<Description>Shared interfaces, models, enumerations and types.</Description> <Description>Shared interfaces, models, enumerations and types.</Description>
<Authors>Stef Heyenrath</Authors> <Authors>Stef Heyenrath</Authors>
<TargetFrameworks>net451;net452;net46;net461;netstandard1.3;netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0</TargetFrameworks> <!--<TargetFrameworks>net451;net452;net46;net461;netstandard1.3;netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0</TargetFrameworks>-->
<TargetFrameworks>net48;net8.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<PackageTags>tdd;mock;http;wiremock;test;server;shared</PackageTags> <PackageTags>tdd;mock;http;wiremock;test;server;shared</PackageTags>
<RootNamespace>WireMock</RootNamespace> <RootNamespace>WireMock</RootNamespace>
@@ -29,7 +30,7 @@
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'netstandard1.3' or '$(TargetFramework)' == 'netstandard2.0' or '$(TargetFramework)' == 'netstandard2.1'"> <!--<PropertyGroup Condition="'$(TargetFramework)' == 'netstandard1.3' or '$(TargetFramework)' == 'netstandard2.0' or '$(TargetFramework)' == 'netstandard2.1'">
<DefineConstants>$(DefineConstants);NETSTANDARD;USE_ASPNETCORE</DefineConstants> <DefineConstants>$(DefineConstants);NETSTANDARD;USE_ASPNETCORE</DefineConstants>
</PropertyGroup> </PropertyGroup>
@@ -39,18 +40,18 @@
<PropertyGroup Condition="'$(TargetFramework)' == 'net461'"> <PropertyGroup Condition="'$(TargetFramework)' == 'net461'">
<DefineConstants>$(DefineConstants);USE_ASPNETCORE;NET46</DefineConstants> <DefineConstants>$(DefineConstants);USE_ASPNETCORE;NET46</DefineConstants>
</PropertyGroup> </PropertyGroup>-->
<ItemGroup> <ItemGroup>
<PackageReference Include="PolySharp" Version="1.15.0"> <PackageReference Include="Polyfill" Version="8.8.0">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Stef.Validation" Version="0.1.1" /> <PackageReference Include="Stef.Validation" Version="0.2.0" />
<PackageReference Include="AnyOf" Version="0.4.0" /> <PackageReference Include="AnyOf" Version="0.5.0.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="1.1.0" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
<PackageReference Include="JsonConverter.Abstractions" Version="0.7.0" /> <PackageReference Include="JsonConverter.Abstractions" Version="0.7.2" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@@ -61,11 +62,12 @@
<PackageReference Include="Handlebars.Net.Helpers.Random" Version="2.5.2" /> <PackageReference Include="Handlebars.Net.Helpers.Random" Version="2.5.2" />
<PackageReference Include="Handlebars.Net.Helpers.Xeger" Version="2.5.2" /> <PackageReference Include="Handlebars.Net.Helpers.Xeger" Version="2.5.2" />
<PackageReference Include="Handlebars.Net.Helpers.XPath" Version="2.5.2" /> <PackageReference Include="Handlebars.Net.Helpers.XPath" Version="2.5.2" />
<PackageReference Include="Handlebars.Net.Helpers.Xslt" Version="2.5.2" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard1.3' "> <!--<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard1.3' ">
<PackageReference Include="System.Reflection.TypeExtensions" Version="4.7.0" /> <PackageReference Include="System.Reflection.TypeExtensions" Version="4.7.0" />
</ItemGroup> </ItemGroup>-->
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\WireMock.Net.Abstractions\WireMock.Net.Abstractions.csproj" /> <ProjectReference Include="..\WireMock.Net.Abstractions\WireMock.Net.Abstractions.csproj" />

View File

@@ -1,9 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<Description>Lightweight StandAlone Http Mocking Server for .Net.</Description> <Description>Lightweight StandAlone Http Mocking Server for .Net.</Description>
<AssemblyTitle>WireMock.Net.StandAlone</AssemblyTitle> <AssemblyTitle>WireMock.Net.StandAlone</AssemblyTitle>
<Authors>Stef Heyenrath</Authors> <Authors>Stef Heyenrath</Authors>
<TargetFrameworks>net451;net452;net46;net461;netstandard1.3;netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0</TargetFrameworks> <!--<TargetFrameworks>net451;net452;net46;net461;netstandard1.3;netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0</TargetFrameworks>-->
<TargetFrameworks>net48;net8.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<AssemblyName>WireMock.Net.StandAlone</AssemblyName> <AssemblyName>WireMock.Net.StandAlone</AssemblyName>
<PackageId>WireMock.Net.StandAlone</PackageId> <PackageId>WireMock.Net.StandAlone</PackageId>
@@ -27,19 +28,26 @@
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(TargetFramework)' == 'netstandard1.3' or '$(TargetFramework)' == 'netstandard2.0' or '$(TargetFramework)' == 'netstandard2.1' "> <!--<PropertyGroup Condition=" '$(TargetFramework)' == 'netstandard1.3' or '$(TargetFramework)' == 'netstandard2.0' or '$(TargetFramework)' == 'netstandard2.1' ">
<DefineConstants>NETSTANDARD;USE_ASPNETCORE</DefineConstants> <DefineConstants>NETSTANDARD;USE_ASPNETCORE</DefineConstants>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'net461'"> <PropertyGroup Condition="'$(TargetFramework)' == 'net461'">
<DefineConstants>USE_ASPNETCORE;NET46</DefineConstants> <DefineConstants>USE_ASPNETCORE;NET46</DefineConstants>
</PropertyGroup> </PropertyGroup>-->
<ItemGroup> <ItemGroup>
<PackageReference Include="PolySharp" Version="1.15.0"> <PackageReference Include="Nullable" Version="1.3.1">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
</ItemGroup>
<ItemGroup>
<!--<PackageReference Include="PolySharp" Version="1.15.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>-->
<ProjectReference Include="..\WireMock.Net\WireMock.Net.csproj" /> <ProjectReference Include="..\WireMock.Net\WireMock.Net.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -27,8 +27,8 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Stef.Validation" Version="0.1.1" /> <PackageReference Include="Stef.Validation" Version="0.2.0" />
<PackageReference Include="TUnit.Core" Version="0.2.195" /> <PackageReference Include="TUnit.Core" Version="0.57.1" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -38,7 +38,7 @@
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Stef.Validation" Version="0.1.1" /> <PackageReference Include="Stef.Validation" Version="0.2.0" />
<PackageReference Include="Testcontainers" Version="4.5.0" /> <PackageReference Include="Testcontainers" Version="4.5.0" />
</ItemGroup> </ItemGroup>

View File

@@ -3,7 +3,8 @@
<Description>Some extensions for xUnit (ITestOutputHelper)</Description> <Description>Some extensions for xUnit (ITestOutputHelper)</Description>
<AssemblyTitle>WireMock.Net.xUnit</AssemblyTitle> <AssemblyTitle>WireMock.Net.xUnit</AssemblyTitle>
<Authors>Stef Heyenrath</Authors> <Authors>Stef Heyenrath</Authors>
<TargetFrameworks>net45;net451;netstandard1.3;netstandard2.0;netstandard2.1</TargetFrameworks> <!--<TargetFrameworks>net45;net451;netstandard1.3;netstandard2.0;netstandard2.1</TargetFrameworks>-->
<TargetFrameworks>net48;net8.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<AssemblyName>WireMock.Net.xUnit</AssemblyName> <AssemblyName>WireMock.Net.xUnit</AssemblyName>
<RootNamespace>WireMock.Net.Xunit</RootNamespace> <RootNamespace>WireMock.Net.Xunit</RootNamespace>

View File

@@ -3,7 +3,8 @@
<Description>Lightweight Http Mocking Server for .NET, inspired by WireMock from the Java landscape.</Description> <Description>Lightweight Http Mocking Server for .NET, inspired by WireMock from the Java landscape.</Description>
<AssemblyTitle>WireMock.Net</AssemblyTitle> <AssemblyTitle>WireMock.Net</AssemblyTitle>
<Authors>Stef Heyenrath</Authors> <Authors>Stef Heyenrath</Authors>
<TargetFrameworks>net451;net452;net46;net461;netstandard1.3;netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0</TargetFrameworks> <!--<TargetFrameworks>net451;net452;net46;net461;netstandard1.3;netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0</TargetFrameworks>-->
<TargetFrameworks>net48;net8.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<AssemblyName>WireMock.Net</AssemblyName> <AssemblyName>WireMock.Net</AssemblyName>
<PackageId>WireMock.Net</PackageId> <PackageId>WireMock.Net</PackageId>
@@ -28,13 +29,22 @@
<CodeAnalysisRuleSet>WireMock.Net.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>WireMock.Net.ruleset</CodeAnalysisRuleSet>
</PropertyGroup> </PropertyGroup>
<PropertyGroup>
<DefineConstants>$(DefineConstants);GRAPHQL;MIMEKIT;PROTOBUF</DefineConstants>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="../WireMock.Net.Minimal/WireMock.Net.Minimal.csproj" /> <ProjectReference Include="../WireMock.Net.Minimal/WireMock.Net.Minimal.csproj" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' != 'netstandard1.3' and '$(TargetFramework)' != 'net451' and '$(TargetFramework)' != 'net452' and '$(TargetFramework)' != 'net46' and '$(TargetFramework)' != 'net461'">
<ProjectReference Include="../WireMock.Net.MimePart/WireMock.Net.MimePart.csproj" /> <ProjectReference Include="../WireMock.Net.MimePart/WireMock.Net.MimePart.csproj" />
<ProjectReference Include="../WireMock.Net.GraphQL/WireMock.Net.GraphQL.csproj" /> <ProjectReference Include="../WireMock.Net.GraphQL/WireMock.Net.GraphQL.csproj" />
<ProjectReference Include="../WireMock.Net.ProtoBuf/WireMock.Net.ProtoBuf.csproj" /> <ProjectReference Include="../WireMock.Net.ProtoBuf/WireMock.Net.ProtoBuf.csproj" />
</ItemGroup> </ItemGroup>
<!--<ItemGroup Condition="'$(TargetFramework)' != 'netstandard1.3' and '$(TargetFramework)' != 'net451' and '$(TargetFramework)' != 'net452' and '$(TargetFramework)' != 'net46' and '$(TargetFramework)' != 'net461'">
<ProjectReference Include="../WireMock.Net.MimePart/WireMock.Net.MimePart.csproj" />
<ProjectReference Include="../WireMock.Net.GraphQL/WireMock.Net.GraphQL.csproj" />
<ProjectReference Include="../WireMock.Net.ProtoBuf/WireMock.Net.ProtoBuf.csproj" />
</ItemGroup>-->
</Project> </Project>

View File

@@ -4,7 +4,8 @@
<Description>Commonly used interfaces, models, enumerations and types.</Description> <Description>Commonly used interfaces, models, enumerations and types.</Description>
<AssemblyTitle>WireMock.Org.Abstractions</AssemblyTitle> <AssemblyTitle>WireMock.Org.Abstractions</AssemblyTitle>
<Authors>Stef Heyenrath</Authors> <Authors>Stef Heyenrath</Authors>
<TargetFrameworks>net45;netstandard1.0;netstandard2.0;netstandard2.1</TargetFrameworks> <!--<TargetFrameworks>net45;netstandard1.0;netstandard2.0;netstandard2.1</TargetFrameworks>-->
<TargetFrameworks>net48;net8.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591;8603</NoWarn> <NoWarn>$(NoWarn);1591;8603</NoWarn>
<RootNamespace>WireMock.Org.Abstractions</RootNamespace> <RootNamespace>WireMock.Org.Abstractions</RootNamespace>

View File

@@ -4,7 +4,8 @@
<Description>A WireMock.org RestClient using RestEase to access the admin interface.</Description> <Description>A WireMock.org RestClient using RestEase to access the admin interface.</Description>
<AssemblyTitle>WireMock.Org.RestClient</AssemblyTitle> <AssemblyTitle>WireMock.Org.RestClient</AssemblyTitle>
<Authors>Stef Heyenrath</Authors> <Authors>Stef Heyenrath</Authors>
<TargetFrameworks>net45;netstandard1.1;netstandard2.0;netstandard2.1</TargetFrameworks> <!--<TargetFrameworks>net45;netstandard1.1;netstandard2.0;netstandard2.1</TargetFrameworks>-->
<TargetFrameworks>net48;net8.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<AssemblyName>WireMock.Org.RestClient</AssemblyName> <AssemblyName>WireMock.Org.RestClient</AssemblyName>
<PackageId>WireMock.Org.RestClient</PackageId> <PackageId>WireMock.Org.RestClient</PackageId>

View File

@@ -1,7 +1,7 @@
<Project> <Project>
<Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" /> <Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" />
<ItemGroup Condition=" '$(TargetFramework)' != 'net45' and '$(TargetFramework)' != 'net452' and '$(TargetFramework)' != 'net461' "> <ItemGroup Condition=" '$(TargetFramework)' != 'net48' ">
<AssemblyAttribute Include="System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute" /> <AssemblyAttribute Include="System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute" />
</ItemGroup> </ItemGroup>

View File

@@ -21,7 +21,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="xunit" Version="2.9.3" /> <PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.3"> <PackageReference Include="xunit.runner.visualstudio" Version="3.1.4">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>

View File

@@ -9,7 +9,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="TUnit" Version="0.2.195" /> <PackageReference Include="TUnit" Version="0.57.1" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -59,7 +59,7 @@ server
) )
.WithGuid("c9929240-7ae8-4a5d-8ed8-0913479f6eeb") .WithGuid("c9929240-7ae8-4a5d-8ed8-0913479f6eeb")
.RespondWith(Response.Create() .RespondWith(Response.Create()
.WithStatusCode(208) .WithStatusCode(306)
.WithBodyAsJson(new .WithBodyAsJson(new
{ {
@as = 1, @as = 1,

View File

@@ -1,6 +1,6 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
#if !(NET452 || NET461 || NETCOREAPP3_1) //#if !(NET452 || NET461 || NETCOREAPP3_1)
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
@@ -69,10 +69,10 @@ public partial class WireMockAdminApiTests
.WithAuthorization(adminUsername, adminPassword); .WithAuthorization(adminUsername, adminPassword);
// Act 1 // Act 1
await api.WaitForHealthAsync().ConfigureAwait(false); await api.WaitForHealthAsync();
// Act 2 // Act 2
var status = await api.GetHealthAsync().ConfigureAwait(false); var status = await api.GetHealthAsync();
status.Should().Be("Healthy"); status.Should().Be("Healthy");
} }
@@ -102,7 +102,7 @@ public partial class WireMockAdminApiTests
var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]);
// Act // Act
var settings = await api.GetSettingsAsync().ConfigureAwait(false); var settings = await api.GetSettingsAsync();
Check.That(settings).IsNotNull(); Check.That(settings).IsNotNull();
} }
@@ -118,7 +118,7 @@ public partial class WireMockAdminApiTests
var api = RestClient.For<IWireMockAdminApi>(server.Urls[0] + "/foo"); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0] + "/foo");
// Act // Act
var settings = await api.GetSettingsAsync().ConfigureAwait(false); var settings = await api.GetSettingsAsync();
// Assert // Assert
Check.That(settings).IsNotNull(); Check.That(settings).IsNotNull();
@@ -137,7 +137,7 @@ public partial class WireMockAdminApiTests
// Act // Act
var settings = new SettingsModel(); var settings = new SettingsModel();
var status = await api.PostSettingsAsync(settings).ConfigureAwait(false); var status = await api.PostSettingsAsync(settings);
Check.That(status.Status).Equals("Settings updated"); Check.That(status.Status).Equals("Settings updated");
} }
@@ -150,7 +150,7 @@ public partial class WireMockAdminApiTests
// Act // Act
var settings = new SettingsModel(); var settings = new SettingsModel();
var status = await api.PutSettingsAsync(settings).ConfigureAwait(false); var status = await api.PutSettingsAsync(settings);
Check.That(status.Status).Equals("Settings updated"); Check.That(status.Status).Equals("Settings updated");
} }
@@ -170,7 +170,7 @@ public partial class WireMockAdminApiTests
Priority = 500, Priority = 500,
Title = "test" Title = "test"
}; };
var result = await api.PutMappingAsync(new Guid("a0000000-0000-0000-0000-000000000000"), model).ConfigureAwait(false); var result = await api.PutMappingAsync(new Guid("a0000000-0000-0000-0000-000000000000"), model);
// Assert // Assert
Check.That(result).IsNotNull(); Check.That(result).IsNotNull();
@@ -200,11 +200,11 @@ public partial class WireMockAdminApiTests
.RespondWith(Response.Create()); .RespondWith(Response.Create());
var serverUrl = "http://localhost:" + server.Ports[0]; var serverUrl = "http://localhost:" + server.Ports[0];
await new HttpClient().GetAsync(serverUrl + "/foo").ConfigureAwait(false); await new HttpClient().GetAsync(serverUrl + "/foo");
var api = RestClient.For<IWireMockAdminApi>(serverUrl); var api = RestClient.For<IWireMockAdminApi>(serverUrl);
// Act // Act
var requests = await api.FindRequestsAsync(new RequestModel { Methods = new[] { "GET" } }).ConfigureAwait(false); var requests = await api.FindRequestsAsync(new RequestModel { Methods = new[] { "GET" } });
// Assert // Assert
requests.Should().HaveCount(1); requests.Should().HaveCount(1);
@@ -231,12 +231,12 @@ public partial class WireMockAdminApiTests
var serverUrl = "http://localhost:" + server.Ports[0]; var serverUrl = "http://localhost:" + server.Ports[0];
using var client = new HttpClient(); using var client = new HttpClient();
await client.GetAsync(serverUrl + "/foo").ConfigureAwait(false); await client.GetAsync(serverUrl + "/foo");
await client.GetAsync(serverUrl + "/foo?bar=baz").ConfigureAwait(false); await client.GetAsync(serverUrl + "/foo?bar=baz");
var api = RestClient.For<IWireMockAdminApi>(serverUrl); var api = RestClient.For<IWireMockAdminApi>(serverUrl);
// Act // Act
var logEntryModels = await api.FindRequestsByMappingGuidAsync(mappingGuid).ConfigureAwait(false); var logEntryModels = await api.FindRequestsByMappingGuidAsync(mappingGuid);
// Assert // Assert
logEntryModels.Should().HaveCount(2); logEntryModels.Should().HaveCount(2);
@@ -270,11 +270,11 @@ public partial class WireMockAdminApiTests
.RespondWith(Response.Create()); .RespondWith(Response.Create());
var serverUrl = "http://localhost:" + server.Ports[0]; var serverUrl = "http://localhost:" + server.Ports[0];
await new HttpClient().GetAsync(serverUrl + "/foo").ConfigureAwait(false); await new HttpClient().GetAsync(serverUrl + "/foo");
var api = RestClient.For<IWireMockAdminApi>(serverUrl); var api = RestClient.For<IWireMockAdminApi>(serverUrl);
// Act // Act
var logEntryModels = await api.FindRequestsByMappingGuidAsync(Guid.NewGuid()).ConfigureAwait(false); var logEntryModels = await api.FindRequestsByMappingGuidAsync(Guid.NewGuid());
// Assert // Assert
logEntryModels.Should().BeEmpty(); logEntryModels.Should().BeEmpty();
@@ -307,11 +307,11 @@ public partial class WireMockAdminApiTests
Logger = new WireMockNullLogger() Logger = new WireMockNullLogger()
}); });
var serverUrl = "http://localhost:" + server.Ports[0]; var serverUrl = "http://localhost:" + server.Ports[0];
await new HttpClient().GetAsync(serverUrl + "/foo").ConfigureAwait(false); await new HttpClient().GetAsync(serverUrl + "/foo");
var api = RestClient.For<IWireMockAdminApi>(serverUrl); var api = RestClient.For<IWireMockAdminApi>(serverUrl);
// Act // Act
var requests = await api.GetRequestsAsync().ConfigureAwait(false); var requests = await api.GetRequestsAsync();
// Assert // Assert
Check.That(requests).HasSize(1); Check.That(requests).HasSize(1);
@@ -347,7 +347,7 @@ public partial class WireMockAdminApiTests
var api = RestClient.For<IWireMockAdminApi>(serverUrl); var api = RestClient.For<IWireMockAdminApi>(serverUrl);
// Act // Act
var requests = await api.GetRequestsAsync().ConfigureAwait(false); var requests = await api.GetRequestsAsync();
// Assert // Assert
Check.That(requests).HasSize(1); Check.That(requests).HasSize(1);
@@ -384,7 +384,7 @@ public partial class WireMockAdminApiTests
}, },
Response = new ResponseModel { Body = "world" } Response = new ResponseModel { Body = "world" }
}; };
var postMappingResult = await api.PostMappingAsync(model).ConfigureAwait(false); var postMappingResult = await api.PostMappingAsync(model);
// Assert // Assert
postMappingResult.Should().NotBeNull(); postMappingResult.Should().NotBeNull();
@@ -392,7 +392,7 @@ public partial class WireMockAdminApiTests
var mapping = server.Mappings.FirstOrDefault(m => m.Guid == guid); var mapping = server.Mappings.FirstOrDefault(m => m.Guid == guid);
mapping.Should().NotBeNull(); mapping.Should().NotBeNull();
var getMappingResult = await api.GetMappingAsync(guid).ConfigureAwait(false); var getMappingResult = await api.GetMappingAsync(guid);
await Verifier.Verify(getMappingResult, VerifySettings).DontScrubGuids(); await Verifier.Verify(getMappingResult, VerifySettings).DontScrubGuids();
@@ -435,7 +435,7 @@ public partial class WireMockAdminApiTests
} }
} }
}; };
var postMappingResult = await api.PostMappingAsync(model).ConfigureAwait(false); var postMappingResult = await api.PostMappingAsync(model);
// Assert // Assert
postMappingResult.Should().NotBeNull(); postMappingResult.Should().NotBeNull();
@@ -443,7 +443,7 @@ public partial class WireMockAdminApiTests
var mapping = server.Mappings.FirstOrDefault(m => m.Guid == guid); var mapping = server.Mappings.FirstOrDefault(m => m.Guid == guid);
mapping.Should().NotBeNull(); mapping.Should().NotBeNull();
var getMappingResult = await api.GetMappingAsync(guid).ConfigureAwait(false); var getMappingResult = await api.GetMappingAsync(guid);
await Verifier.Verify(getMappingResult, VerifySettings).DontScrubGuids(); await Verifier.Verify(getMappingResult, VerifySettings).DontScrubGuids();
@@ -475,7 +475,7 @@ public partial class WireMockAdminApiTests
var api = RestClient.For<IWireMockAdminApi>(serverUrl); var api = RestClient.For<IWireMockAdminApi>(serverUrl);
// Act // Act
var requests = await api.GetRequestsAsync().ConfigureAwait(false); var requests = await api.GetRequestsAsync();
// Assert // Assert
Check.That(requests).HasSize(1); Check.That(requests).HasSize(1);
@@ -504,7 +504,7 @@ public partial class WireMockAdminApiTests
var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]);
// Act // Act
var request = await api.PostFileAsync("filename.txt", "abc").ConfigureAwait(false); var request = await api.PostFileAsync("filename.txt", "abc");
// Assert // Assert
Check.That(request.Guid).IsNull(); Check.That(request.Guid).IsNull();
@@ -537,7 +537,7 @@ public partial class WireMockAdminApiTests
var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]);
// Act // Act
var request = await api.PutFileAsync("filename.txt", "abc-abc").ConfigureAwait(false); var request = await api.PutFileAsync("filename.txt", "abc-abc");
// Assert // Assert
Check.That(request.Guid).IsNull(); Check.That(request.Guid).IsNull();
@@ -568,7 +568,7 @@ public partial class WireMockAdminApiTests
var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]);
// Act and Assert // Act and Assert
Check.ThatAsyncCode(() => api.PutFileAsync("filename.txt", "xxx")).Throws<ApiException>(); Check.ThatCode(() => api.PutFileAsync("filename.txt", "xxx")).Throws<ApiException>();
// Verify // Verify
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once); filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
@@ -595,7 +595,7 @@ public partial class WireMockAdminApiTests
var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]);
// Act and Assert // Act and Assert
Check.ThatAsyncCode(() => api.GetFileAsync("filename.txt")).Throws<ApiException>(); Check.ThatCode(() => api.GetFileAsync("filename.txt")).Throws<ApiException>();
// Verify // Verify
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once); filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
@@ -623,7 +623,7 @@ public partial class WireMockAdminApiTests
var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]);
// Act // Act
string file = await api.GetFileAsync("filename.txt").ConfigureAwait(false); string file = await api.GetFileAsync("filename.txt");
// Assert // Assert
Check.That(file).Equals(data); Check.That(file).Equals(data);
@@ -654,7 +654,7 @@ public partial class WireMockAdminApiTests
var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]);
// Act // Act
await api.DeleteFileAsync("filename.txt").ConfigureAwait(false); await api.DeleteFileAsync("filename.txt");
// Verify // Verify
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once); filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
@@ -682,7 +682,7 @@ public partial class WireMockAdminApiTests
var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]);
// Act and Assert // Act and Assert
Check.ThatAsyncCode(() => api.DeleteFileAsync("filename.txt")).Throws<ApiException>(); Check.ThatCode(() => api.DeleteFileAsync("filename.txt")).Throws<ApiException>();
// Verify // Verify
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once); filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
@@ -708,7 +708,7 @@ public partial class WireMockAdminApiTests
var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]);
// Act and Assert // Act and Assert
Check.ThatAsyncCode(() => api.FileExistsAsync("filename.txt")).Throws<ApiException>(); Check.ThatCode(() => api.FileExistsAsync("filename.txt")).Throws<ApiException>();
// Verify // Verify
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once); filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
@@ -726,7 +726,7 @@ public partial class WireMockAdminApiTests
var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]);
// Act // Act
var status = await api.DeleteScenarioAsync(name).ConfigureAwait(false); var status = await api.DeleteScenarioAsync(name);
status.Status.Should().Be("No scenario found by name 'x'."); status.Status.Should().Be("No scenario found by name 'x'.");
} }
@@ -739,7 +739,7 @@ public partial class WireMockAdminApiTests
var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]);
// Act // Act
var status = await api.ResetScenarioAsync(name).ConfigureAwait(false); var status = await api.ResetScenarioAsync(name);
status.Status.Should().Be("No scenario found by name 'x'."); status.Status.Should().Be("No scenario found by name 'x'.");
} }
@@ -756,7 +756,7 @@ public partial class WireMockAdminApiTests
{ {
State = null State = null
}; };
var status = await api.PutScenarioStateAsync("x", update).ConfigureAwait(false); var status = await api.PutScenarioStateAsync("x", update);
status.Status.Should().Be("No scenario found by name 'x'."); status.Status.Should().Be("No scenario found by name 'x'.");
} }
@@ -790,7 +790,7 @@ public partial class WireMockAdminApiTests
{ {
State = null State = null
}; };
var status = await api.PutScenarioStateAsync("s1", update).ConfigureAwait(false); var status = await api.PutScenarioStateAsync("s1", update);
status.Status.Should().Be("Scenario state set to ''"); status.Status.Should().Be("Scenario state set to ''");
} }
@@ -817,7 +817,7 @@ public partial class WireMockAdminApiTests
// Act // Act
var api = RestClient.For<IWireMockAdminApi>(server.Url); var api = RestClient.For<IWireMockAdminApi>(server.Url);
var getMappingResult = await api.GetMappingAsync(guid).ConfigureAwait(false); var getMappingResult = await api.GetMappingAsync(guid);
// Assert // Assert
var mapping = server.Mappings.FirstOrDefault(m => m.Guid == guid); var mapping = server.Mappings.FirstOrDefault(m => m.Guid == guid);
@@ -852,10 +852,10 @@ public partial class WireMockAdminApiTests
// Act // Act
var api = RestClient.For<IWireMockAdminApi>(server.Url); var api = RestClient.For<IWireMockAdminApi>(server.Url);
var mappings = await api.GetMappingsAsync().ConfigureAwait(false); var mappings = await api.GetMappingsAsync();
mappings.Should().HaveCount(1); mappings.Should().HaveCount(1);
var code = await api.GetMappingCodeAsync(guid).ConfigureAwait(false); var code = await api.GetMappingCodeAsync(guid);
// Assert // Assert
await Verifier.Verify(code).DontScrubDateTimes().DontScrubGuids(); await Verifier.Verify(code).DontScrubDateTimes().DontScrubGuids();
@@ -942,7 +942,7 @@ public partial class WireMockAdminApiTests
.WithGuid(guid5) .WithGuid(guid5)
.RespondWith( .RespondWith(
Response.Create() Response.Create()
.WithStatusCode(HttpStatusCode.AlreadyReported) .WithStatusCode(HttpStatusCode.Unused)
.WithBodyAsJson(new .WithBodyAsJson(new
{ {
@as = 1, @as = 1,
@@ -974,10 +974,10 @@ text
// Act // Act
var api = RestClient.For<IWireMockAdminApi>(server.Url); var api = RestClient.For<IWireMockAdminApi>(server.Url);
var mappings = await api.GetMappingsAsync().ConfigureAwait(false); var mappings = await api.GetMappingsAsync();
mappings.Should().HaveCount(5); mappings.Should().HaveCount(5);
var code = await api.GetMappingsCodeAsync().ConfigureAwait(false); var code = await api.GetMappingsCodeAsync();
// Assert // Assert
await Verifier.Verify(code).DontScrubDateTimes().DontScrubGuids(); await Verifier.Verify(code).DontScrubDateTimes().DontScrubGuids();
@@ -989,13 +989,13 @@ text
public async Task IWireMockAdminApi_OpenApiConvert_Yml() public async Task IWireMockAdminApi_OpenApiConvert_Yml()
{ {
// Arrange // Arrange
var openApiDocument = await File.ReadAllTextAsync(Path.Combine("OpenApiParser", "petstore.yml")); var openApiDocument = File.ReadAllText(Path.Combine("OpenApiParser", "petstore.yml"));
var server = WireMockServer.StartWithAdminInterface(); var server = WireMockServer.StartWithAdminInterface();
var api = RestClient.For<IWireMockAdminApi>(server.Url); var api = RestClient.For<IWireMockAdminApi>(server.Url);
// Act // Act
var mappings = await api.OpenApiConvertAsync(openApiDocument).ConfigureAwait(false); var mappings = await api.OpenApiConvertAsync(openApiDocument);
// Assert // Assert
server.MappingModels.Should().BeEmpty(); server.MappingModels.Should().BeEmpty();
@@ -1008,13 +1008,13 @@ text
public async Task IWireMockAdminApi_OpenApiConvert_Json() public async Task IWireMockAdminApi_OpenApiConvert_Json()
{ {
// Arrange // Arrange
var openApiDocument = await File.ReadAllTextAsync(Path.Combine("OpenApiParser", "petstore-openapi3.json")); var openApiDocument = File.ReadAllText(Path.Combine("OpenApiParser", "petstore-openapi3.json"));
var server = WireMockServer.StartWithAdminInterface(); var server = WireMockServer.StartWithAdminInterface();
var api = RestClient.For<IWireMockAdminApi>(server.Url); var api = RestClient.For<IWireMockAdminApi>(server.Url);
// Act // Act
var mappings = await api.OpenApiConvertAsync(openApiDocument).ConfigureAwait(false); var mappings = await api.OpenApiConvertAsync(openApiDocument);
// Assert // Assert
server.MappingModels.Should().BeEmpty(); server.MappingModels.Should().BeEmpty();
@@ -1027,13 +1027,13 @@ text
public async Task IWireMockAdminApi_OpenApiSave_Json() public async Task IWireMockAdminApi_OpenApiSave_Json()
{ {
// Arrange // Arrange
var openApiDocument = await File.ReadAllTextAsync(Path.Combine("OpenApiParser", "petstore-openapi3.json")); var openApiDocument = File.ReadAllText(Path.Combine("OpenApiParser", "petstore-openapi3.json"));
var server = WireMockServer.StartWithAdminInterface(); var server = WireMockServer.StartWithAdminInterface();
var api = RestClient.For<IWireMockAdminApi>(server.Url); var api = RestClient.For<IWireMockAdminApi>(server.Url);
// Act // Act
var statusModel = await api.OpenApiSaveAsync(openApiDocument).ConfigureAwait(false); var statusModel = await api.OpenApiSaveAsync(openApiDocument);
// Assert // Assert
statusModel.Status.Should().Be("OpenApi document converted to Mappings"); statusModel.Status.Should().Be("OpenApi document converted to Mappings");
@@ -1046,13 +1046,13 @@ text
public async Task IWireMockAdminApi_OpenApiSave_Yml() public async Task IWireMockAdminApi_OpenApiSave_Yml()
{ {
// Arrange // Arrange
var openApiDocument = await File.ReadAllTextAsync(Path.Combine("OpenApiParser", "petstore.yml")); var openApiDocument = File.ReadAllText(Path.Combine("OpenApiParser", "petstore.yml"));
var server = WireMockServer.StartWithAdminInterface(); var server = WireMockServer.StartWithAdminInterface();
var api = RestClient.For<IWireMockAdminApi>(server.Url); var api = RestClient.For<IWireMockAdminApi>(server.Url);
// Act // Act
var mappings = await api.OpenApiConvertAsync(openApiDocument).ConfigureAwait(false); var mappings = await api.OpenApiConvertAsync(openApiDocument);
// Assert // Assert
server.MappingModels.Should().BeEmpty(); server.MappingModels.Should().BeEmpty();
@@ -1069,7 +1069,7 @@ text
var api = RestClient.For<IWireMockAdminApi>(server.Url); var api = RestClient.For<IWireMockAdminApi>(server.Url);
// Act // Act
var status = await api.ReloadStaticMappingsAsync().ConfigureAwait(false); var status = await api.ReloadStaticMappingsAsync();
// Assert // Assert
status.Status.Should().Be("Static Mappings reloaded"); status.Status.Should().Be("Static Mappings reloaded");
@@ -1080,4 +1080,4 @@ text
return File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "__admin", "mappings", filename)); return File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "__admin", "mappings", filename));
} }
} }
#endif //#endif

View File

@@ -5,6 +5,7 @@ using System.Linq;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using FluentAssertions; using FluentAssertions;
using WireMock.FluentAssertions; using WireMock.FluentAssertions;

View File

@@ -1,6 +1,6 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
#if PROTOBUF //#if PROTOBUF
using System; using System;
using System.IO; using System.IO;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -18,8 +18,8 @@ public class ProtoBufUtilsTests
public async Task GetProtoBufMessageWithHeader_MultipleProtoFiles() public async Task GetProtoBufMessageWithHeader_MultipleProtoFiles()
{ {
// Arrange // Arrange
var greet = await ReadProtoFileAsync("greet1.proto"); var greet = ReadProtoFile("greet1.proto");
var request = await ReadProtoFileAsync("request.proto"); var request = ReadProtoFile("request.proto");
// Act // Act
var responseBytes = await ProtoBufUtils.GetProtoBufMessageWithHeaderAsync( var responseBytes = await ProtoBufUtils.GetProtoBufMessageWithHeaderAsync(
@@ -35,9 +35,9 @@ public class ProtoBufUtilsTests
Convert.ToBase64String(responseBytes).Should().Be("AAAAAAcKBWhlbGxv"); Convert.ToBase64String(responseBytes).Should().Be("AAAAAAcKBWhlbGxv");
} }
private static Task<string> ReadProtoFileAsync(string filename) private string ReadProtoFile(string filename)
{ {
return File.ReadAllTextAsync(Path.Combine(Directory.GetCurrentDirectory(), "Grpc", filename)); return File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "Grpc", filename));
} }
} }
#endif //#endif

View File

@@ -1,6 +1,6 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
#if PROTOBUF //#if PROTOBUF
using System; using System;
using System.IO; using System.IO;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -72,4 +72,4 @@ public class ProtoDefinitionHelperTests
Convert.ToBase64String(responseBytes).Should().Be("AAAAAAcIARIDYWJj"); Convert.ToBase64String(responseBytes).Should().Be("AAAAAAcIARIDYWJj");
} }
} }
#endif //#endif

View File

@@ -1,6 +1,6 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
#if PROTOBUF //#if PROTOBUF
using System; using System;
using System.IO; using System.IO;
using System.Net; using System.Net;
@@ -501,7 +501,7 @@ message Other {
public async Task WireMockServer_WithBodyAsProtoBuf_WithWellKnownTypes_Empty_UsingGrpcGeneratedClient() public async Task WireMockServer_WithBodyAsProtoBuf_WithWellKnownTypes_Empty_UsingGrpcGeneratedClient()
{ {
// Arrange // Arrange
var definition = await File.ReadAllTextAsync("./Grpc/greet.proto"); var definition = File.ReadAllText("./Grpc/greet.proto");
using var server = WireMockServer.Start(useHttp2: true); using var server = WireMockServer.Start(useHttp2: true);
@@ -534,7 +534,7 @@ message Other {
// Arrange // Arrange
const int seconds = 1722301323; const int seconds = 1722301323;
const int nanos = 12300; const int nanos = 12300;
var definition = await File.ReadAllTextAsync("./Grpc/greet.proto"); var definition = File.ReadAllText("./Grpc/greet.proto");
using var server = WireMockServer.Start(useHttp2: true); using var server = WireMockServer.Start(useHttp2: true);
@@ -575,7 +575,7 @@ message Other {
// Arrange // Arrange
const int seconds = 1722301323; const int seconds = 1722301323;
const int nanos = 12300; const int nanos = 12300;
var definition = await File.ReadAllTextAsync("./Grpc/greet.proto"); var definition = File.ReadAllText("./Grpc/greet.proto");
using var server = WireMockServer.Start(useHttp2: true); using var server = WireMockServer.Start(useHttp2: true);
@@ -614,7 +614,7 @@ message Other {
public async Task WireMockServer_WithBodyAsProtoBuf_Enum_UsingGrpcGeneratedClient() public async Task WireMockServer_WithBodyAsProtoBuf_Enum_UsingGrpcGeneratedClient()
{ {
// Arrange // Arrange
var definition = await File.ReadAllTextAsync("./Grpc/greet.proto"); var definition = File.ReadAllText("./Grpc/greet.proto");
using var server = WireMockServer.Start(useHttp2: true); using var server = WireMockServer.Start(useHttp2: true);
@@ -655,7 +655,7 @@ message Other {
const int nanos = 12300; const int nanos = 12300;
const string version = "test"; const string version = "test";
const string correlationId = "correlation"; const string correlationId = "correlation";
var definition = await File.ReadAllTextAsync("./Grpc/policy.proto"); var definition = File.ReadAllText("./Grpc/policy.proto");
using var server = WireMockServer.Start(useHttp2: true); using var server = WireMockServer.Start(useHttp2: true);
@@ -773,4 +773,4 @@ message Other {
return File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "Grpc", filename)); return File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "Grpc", filename));
} }
} }
#endif //#endif

View File

@@ -1,6 +1,6 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
#if MIMEKIT //#if MIMEKIT
using System; using System;
using FluentAssertions; using FluentAssertions;
using WireMock.Matchers; using WireMock.Matchers;
@@ -100,4 +100,4 @@ public class MimePartMatcherTests
result.Score.Should().Be(MatchScores.Perfect); result.Score.Should().Be(MatchScores.Perfect);
} }
} }
#endif //#endif

View File

@@ -1,6 +1,6 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
#if GRAPHQL //#if GRAPHQL
using System; using System;
using FluentAssertions; using FluentAssertions;
using WireMock.GraphQL.Models; using WireMock.GraphQL.Models;
@@ -95,4 +95,4 @@ public class WireMockCustomScalarGraphTypeTests
result.Should().Be("someString"); result.Should().Be("someString");
} }
} }
#endif //#endif

View File

@@ -1,4 +1,4 @@
#if !(NET452 || NET461 || NETCOREAPP3_1) //#if !(NET452 || NET461 || NETCOREAPP3_1)
using System; using System;
using System.IO; using System.IO;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -40,7 +40,7 @@ public class WireMockOpenApiParserTests
ExampleValues = _exampleValuesMock.Object ExampleValues = _exampleValuesMock.Object
}; };
var openApiDocument = await File.ReadAllTextAsync(Path.Combine("OpenApiParser", "payroc-openapi-spec.yaml")); var openApiDocument = File.ReadAllText(Path.Combine("OpenApiParser", "payroc-openapi-spec.yaml"));
// Act // Act
var mappings = _sut.FromText(openApiDocument, settings, out _); var mappings = _sut.FromText(openApiDocument, settings, out _);
@@ -58,7 +58,7 @@ public class WireMockOpenApiParserTests
ExampleValues = _exampleValuesMock.Object ExampleValues = _exampleValuesMock.Object
}; };
var openApiDocument = await File.ReadAllTextAsync(Path.Combine("OpenApiParser", "oas-content-example.json")); var openApiDocument = File.ReadAllText(Path.Combine("OpenApiParser", "oas-content-example.json"));
// Act // Act
var mappings = _sut.FromText(openApiDocument, settings, out _); var mappings = _sut.FromText(openApiDocument, settings, out _);
@@ -67,4 +67,4 @@ public class WireMockOpenApiParserTests
await Verifier.Verify(mappings); await Verifier.Verify(mappings);
} }
} }
#endif //#endif

View File

@@ -39,7 +39,7 @@ namespace WireMock.Net.Tests.Owin
public void GlobalExceptionMiddleware_Invoke_NullAsNext_DoesNotInvokeNextAndDoesNotThrow() public void GlobalExceptionMiddleware_Invoke_NullAsNext_DoesNotInvokeNextAndDoesNotThrow()
{ {
// Act // Act
Check.ThatAsyncCode(() => _sut.Invoke(null)).DoesNotThrow(); Check.ThatCode(() => _sut.Invoke(null)).DoesNotThrow();
} }
} }
} }

View File

@@ -1,6 +1,6 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
#if MIMEKIT //#if MIMEKIT
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@@ -178,4 +178,4 @@ AAAADElEQVR4XmMQYNgAAADkAMHebX3mAAAAAElFTkSuQmCC
return matcher.GetMatchingScore(requestMessage, result); return matcher.GetMatchingScore(requestMessage, result);
} }
} }
#endif //#endif

View File

@@ -105,7 +105,7 @@ public class ResponseWithHandlebarsFileTests
.WithTransformer(); .WithTransformer();
// Act // Act
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings)).Throws<HandlebarsException>(); Check.ThatCode(() => responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings)).Throws<HandlebarsException>();
// Verify // Verify
_filesystemHandlerMock.Verify(fs => fs.ReadResponseBodyAsString(It.IsAny<string>()), Times.Never); _filesystemHandlerMock.Verify(fs => fs.ReadResponseBodyAsString(It.IsAny<string>()), Times.Never);

View File

@@ -350,7 +350,7 @@ public class ResponseWithHandlebarsJsonPathTests
.WithTransformer(); .WithTransformer();
// Act // Act
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings)).Throws<ArgumentNullException>(); Check.ThatCode(() => responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings)).Throws<ArgumentNullException>();
} }
[Fact] [Fact]

View File

@@ -162,7 +162,7 @@ public class ResponseWithHandlebarsLinqTests
.WithTransformer(); .WithTransformer();
// Act // Act
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings)).Throws<ArgumentException>(); Check.ThatCode(() => responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings)).Throws<ArgumentException>();
} }
[Fact] [Fact]
@@ -178,7 +178,7 @@ public class ResponseWithHandlebarsLinqTests
.WithTransformer(); .WithTransformer();
// Act // Act
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings)).Throws<HandlebarsException>(); Check.ThatCode(() => responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings)).Throws<HandlebarsException>();
} }
[Fact] [Fact]

View File

@@ -120,6 +120,6 @@ public class ResponseWithHandlebarsRegexTests
.WithTransformer(); .WithTransformer();
// Act and Assert // Act and Assert
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings)).Throws<ArgumentNullException>(); Check.ThatCode(() => responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings)).Throws<ArgumentNullException>();
} }
} }

View File

@@ -84,7 +84,7 @@ public class ResponseWithProxyTests : IDisposable
// Act // Act
var request = new RequestMessage(new UrlDetails($"{_server.Urls[0]}/{_guid}"), "GET", ClientIp); var request = new RequestMessage(new UrlDetails($"{_server.Urls[0]}/{_guid}"), "GET", ClientIp);
Check.ThatAsyncCode(() => responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings)).Throws<HttpRequestException>(); Check.ThatCode(() => responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings)).Throws<HttpRequestException>();
} }
public void Dispose() public void Dispose()

View File

@@ -779,7 +779,7 @@ public class ResponseWithTransformerTests
response.Message.BodyData.Encoding.Should().Be(enc); response.Message.BodyData.Encoding.Should().Be(enc);
} }
#if MIMEKIT //#if MIMEKIT
[Theory] [Theory]
[InlineData(TransformerType.Handlebars)] [InlineData(TransformerType.Handlebars)]
// [InlineData(TransformerType.Scriban)] // [InlineData(TransformerType.Scriban)]
@@ -825,12 +825,12 @@ AAAADElEQVR4XmMQYNgAAADkAMHebX3mAAAAAElFTkSuQmCC
.WithTransformer(transformerType); .WithTransformer(transformerType);
// Act // Act
var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings).ConfigureAwait(false); var response = await responseBuilder.ProvideResponseAsync(_mappingMock.Object, request, _settings);
// Assert // Assert
response.Message.BodyData!.BodyAsString.Should().Be("text/plain text/json image.png"); response.Message.BodyData!.BodyAsString.Should().Be("text/plain text/json image.png");
} }
#endif //#endif
[Theory] [Theory]
[InlineData("/wiremock-data/1", "one")] [InlineData("/wiremock-data/1", "one")]

View File

@@ -62,7 +62,7 @@ public class MatcherMapperTests
models.Should().HaveCount(2); models.Should().HaveCount(2);
} }
#if MIMEKIT //#if MIMEKIT
[Fact] [Fact]
public void MatcherMapper_Map_Matcher_MimePartMatcher() public void MatcherMapper_Map_Matcher_MimePartMatcher()
{ {
@@ -94,7 +94,7 @@ public class MatcherMapperTests
model.ContentMatcher!.Name.Should().Be(nameof(ExactObjectMatcher)); model.ContentMatcher!.Name.Should().Be(nameof(ExactObjectMatcher));
model.ContentMatcher.Pattern.Should().Be(bytes); model.ContentMatcher.Pattern.Should().Be(bytes);
} }
#endif //#endif
[Fact] [Fact]
public void MatcherMapper_Map_Matcher_IStringMatcher() public void MatcherMapper_Map_Matcher_IStringMatcher()
@@ -598,7 +598,7 @@ message HelloReply {
matcher.MatchBehaviour.Should().Be(MatchBehaviour.RejectOnMatch); matcher.MatchBehaviour.Should().Be(MatchBehaviour.RejectOnMatch);
} }
#if MIMEKIT //#if MIMEKIT
[Fact] [Fact]
public void MatcherMapper_Map_MatcherModel_MimePartMatcher() public void MatcherMapper_Map_MatcherModel_MimePartMatcher()
{ {
@@ -638,7 +638,7 @@ message HelloReply {
matcher.ContentTransferEncodingMatcher.Should().BeAssignableTo<RegexMatcher>().Which.GetPatterns().Should().ContainSingle("z"); matcher.ContentTransferEncodingMatcher.Should().BeAssignableTo<RegexMatcher>().Which.GetPatterns().Should().ContainSingle("z");
matcher.ContentTypeMatcher.Should().BeAssignableTo<ContentTypeMatcher>().Which.GetPatterns().Should().ContainSingle("text/json"); matcher.ContentTypeMatcher.Should().BeAssignableTo<ContentTypeMatcher>().Which.GetPatterns().Should().ContainSingle("text/json");
} }
#endif //#endif
[Fact] [Fact]
public void MatcherMapper_Map_MatcherModel_XPathMatcher_WithXmlNamespaces_As_String() public void MatcherMapper_Map_MatcherModel_XPathMatcher_WithXmlNamespaces_As_String()

View File

@@ -2,7 +2,7 @@
<PropertyGroup> <PropertyGroup>
<Authors>Stef Heyenrath</Authors> <Authors>Stef Heyenrath</Authors>
<TargetFrameworks>net452;net461;net6.0;net8.0</TargetFrameworks> <TargetFrameworks>net48;net8.0</TargetFrameworks>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<IsPackable>false</IsPackable> <IsPackable>false</IsPackable>
<DebugType>full</DebugType> <DebugType>full</DebugType>
@@ -21,15 +21,19 @@
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType> <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'net452' or '$(TargetFramework)' == 'net461'"> <!--<PropertyGroup Condition="'$(TargetFramework)' == 'net452' or '$(TargetFramework)' == 'net461'">
<DefineConstants>NETFRAMEWORK</DefineConstants> <DefineConstants>NETFRAMEWORK</DefineConstants>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' != 'netstandard1.3' and '$(TargetFramework)' != 'net451' and '$(TargetFramework)' != 'net452' and '$(TargetFramework)' != 'net46' and '$(TargetFramework)' != 'net461'"> <PropertyGroup Condition="'$(TargetFramework)' != 'netstandard1.3' and '$(TargetFramework)' != 'net451' and '$(TargetFramework)' != 'net452' and '$(TargetFramework)' != 'net46' and '$(TargetFramework)' != 'net461'">
<DefineConstants>$(DefineConstants);GRAPHQL;MIMEKIT;PROTOBUF</DefineConstants> <DefineConstants>$(DefineConstants);GRAPHQL;MIMEKIT;PROTOBUF</DefineConstants>
</PropertyGroup>-->
<PropertyGroup>
<DefineConstants>$(DefineConstants);GRAPHQL;MIMEKIT;PROTOBUF</DefineConstants>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' != 'netstandard1.3' and '$(TargetFramework)' != 'net451' and '$(TargetFramework)' != 'net452' and '$(TargetFramework)' != 'net46' "> <PropertyGroup Condition=" '$(TargetFramework)' != 'net48' ">
<DefineConstants>$(DefineConstants);TRAILINGHEADERS</DefineConstants> <DefineConstants>$(DefineConstants);TRAILINGHEADERS</DefineConstants>
</PropertyGroup> </PropertyGroup>
@@ -64,21 +68,40 @@
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="CultureAwareTesting.xUnit" Version="0.0.1" /> <PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.4.0" /> <PackageReference Include="xunit.core" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="CultureAwareTesting.xUnit" Version="0.0.1.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="coverlet.collector" Version="3.2.0"> <PackageReference Include="coverlet.collector" Version="3.2.0">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Moq" Version="4.17.2" /> <PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="System.Threading" Version="4.3.0" /> <!--<PackageReference Include="System.Threading" Version="4.3.0" />-->
<PackageReference Include="NFluent" Version="2.8.0" /> <PackageReference Include="NFluent" Version="3.1.0" />
<PackageReference Include="SimMetrics.Net" Version="1.0.5" /> <PackageReference Include="SimMetrics.Net" Version="1.0.5" />
<PackageReference Include="AnyOf" Version="0.4.0" />
<PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="5.2.9" /> <PackageReference Include="Verify.Xunit" Version="19.6.0" />
<PackageReference Include="JsonConverter.System.Text.Json" Version="0.7.2" />
<PackageReference Include="Google.Protobuf" Version="3.25.1" />
<PackageReference Include="Grpc.Net.Client" Version="2.60.0" />
<PackageReference Include="Grpc.Tools" Version="2.60.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<Protobuf Include="Grpc\greet.proto" GrpcServices="Client" />
<Protobuf Include="Grpc\policy.proto" GrpcServices="Client" />
<!--<PackageReference Include="AnyOf" Version="0.4.0" />-->
<!--<PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="5.2.9" />-->
</ItemGroup> </ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net452' or '$(TargetFramework)' == 'net461'"> <!--<ItemGroup Condition="'$(TargetFramework)' == 'net452' or '$(TargetFramework)' == 'net461'">
<PackageReference Include="Microsoft.Owin.Host.HttpListener" Version="3.1.0" /> <PackageReference Include="Microsoft.Owin.Host.HttpListener" Version="3.1.0" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" /> <PackageReference Include="System.ValueTuple" Version="4.5.0" />
<PackageReference Include="FluentAssertions" Version="5.10.3" /> <PackageReference Include="FluentAssertions" Version="5.10.3" />
@@ -99,9 +122,9 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Verify.Xunit" Version="19.6.0" /> <PackageReference Include="Verify.Xunit" Version="19.6.0" />
</ItemGroup> </ItemGroup>-->
<ItemGroup Condition="'$(TargetFramework)' != 'net452'"> <!--<ItemGroup Condition="'$(TargetFramework)' != 'net452'">
<PackageReference Include="System.Net.Http.Json" Version="8.0.1" /> <PackageReference Include="System.Net.Http.Json" Version="8.0.1" />
<PackageReference Include="JsonConverter.System.Text.Json" Version="0.7.0" /> <PackageReference Include="JsonConverter.System.Text.Json" Version="0.7.0" />
<PackageReference Include="Google.Protobuf" Version="3.25.1" /> <PackageReference Include="Google.Protobuf" Version="3.25.1" />
@@ -113,9 +136,18 @@
<Protobuf Include="Grpc\greet.proto" GrpcServices="Client" /> <Protobuf Include="Grpc\greet.proto" GrpcServices="Client" />
<Protobuf Include="Grpc\policy.proto" GrpcServices="Client" /> <Protobuf Include="Grpc\policy.proto" GrpcServices="Client" />
</ItemGroup>-->
<ItemGroup>
<!--<PackageReference Include="System.Net.Http.Json" Version="8.0.1" />-->
</ItemGroup> </ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net6.0' or '$(TargetFramework)' == 'net7.0' or '$(TargetFramework)' == 'net8.0'"> <!--<ItemGroup Condition="'$(TargetFramework)' == 'net6.0' or '$(TargetFramework)' == 'net7.0' or '$(TargetFramework)' == 'net8.0'">
<ProjectReference Include="..\..\src\WireMock.Net.Testcontainers\WireMock.Net.Testcontainers.csproj" />
</ItemGroup>-->
<ItemGroup>
<ProjectReference Include="..\..\src\WireMock.Net.Testcontainers\WireMock.Net.Testcontainers.csproj" /> <ProjectReference Include="..\..\src\WireMock.Net.Testcontainers\WireMock.Net.Testcontainers.csproj" />
</ItemGroup> </ItemGroup>
@@ -133,26 +165,26 @@
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>
<None Update="Grpc\Test\greet.proto"> <None Update="Grpc\Test\greet.proto">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>
<None Update="Grpc\request.proto"> <None Update="Grpc\request.proto">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<!--<GrpcServices>Client</GrpcServices>--> <!--<GrpcServices>Client</GrpcServices>-->
</None> </None>
<None Update="Grpc\greet1.proto"> <None Update="Grpc\greet1.proto">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<!--<GrpcServices>Client</GrpcServices>--> <!--<GrpcServices>Client</GrpcServices>-->
</None> </None>
<None Update="Grpc\policy.proto"> <None Update="Grpc\policy.proto">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<GrpcServices>Client</GrpcServices> <GrpcServices>Client</GrpcServices>
</None> </None>
<None Update="Grpc\greet.proto"> <None Update="Grpc\greet.proto">
<GrpcServices>Client</GrpcServices> <GrpcServices>Client</GrpcServices>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>
<None Update="Grpc\Test\SubFolder\request.proto"> <None Update="Grpc\Test\SubFolder\request.proto">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None> </None>
<None Update="Grpc\ot\opentelemetry\proto\**\*.proto"> <None Update="Grpc\ot\opentelemetry\proto\**\*.proto">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>

View File

@@ -1,7 +1,6 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
#if !NET451 && !NET452 //#if !NET451 && !NET452
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
@@ -49,13 +48,10 @@ public partial class WireMockServerTests
httpMessageHandler.ClientCertificates.AddRange(certificates); httpMessageHandler.ClientCertificates.AddRange(certificates);
// Act // Act
var response = await new HttpClient(httpMessageHandler) var response = await new HttpClient(httpMessageHandler).GetAsync("https://localhost:" + server.Ports[0] + "/foo");
.GetAsync("https://localhost:" + server.Ports[0] + "/foo")
.ConfigureAwait(false);
// Assert // Assert
response.StatusCode.Should().Be(HttpStatusCode.OK); response.StatusCode.Should().Be(HttpStatusCode.OK);
} }
} }
//#endif
#endif

View File

@@ -7,6 +7,7 @@ using System.IO;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Net.Http.Headers; using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text; using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
using FluentAssertions; using FluentAssertions;

View File

@@ -1,6 +1,6 @@
// Copyright © WireMock.Net // Copyright © WireMock.Net
#if MIMEKIT //#if MIMEKIT
using System; using System;
using System.Net; using System.Net;
using System.Net.Http; using System.Net.Http;
@@ -74,4 +74,4 @@ public partial class WireMockServerTests
server.Stop(); server.Stop();
} }
} }
#endif //#endif

View File

@@ -102,7 +102,7 @@ public partial class WireMockServerTests
// then // then
Check.That(server.Mappings).IsEmpty(); Check.That(server.Mappings).IsEmpty();
Check.ThatAsyncCode(() => new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + path)).ThrowsAny(); Check.ThatCode(() => new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + path)).ThrowsAny();
server.Stop(); server.Stop();
} }