Skip to content
This repository was archived by the owner on Jan 21, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/Microsoft.HttpRepl/Commands/ConnectCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ public class ConnectCommand : CommandWithStructuredInputBase<HttpState, ICorePar
private const string BaseAddressOption = nameof(BaseAddressOption);
private const string SwaggerAddressOption = nameof(SwaggerAddressOption);
private const string Name = "connect";
private const string WebApiDefaultPathSuffix = "/swagger/";

private readonly IPreferences _preferences;

Expand Down Expand Up @@ -136,6 +137,18 @@ private static ApiConnection GetConnectionInfo(IShellState shellState, HttpState
ApiConnection apiConnection = new ApiConnection(preferences);
if (!string.IsNullOrWhiteSpace(rootAddress))
{
// The `dotnet new webapi` template now has a default start url of `swagger`. Because
// the default Swashbuckle-generated OpenAPI description doesn't contain a Servers element
// this will put HttpRepl users into a pit of failure by having a base address of
// https://localhost:{port}/swagger/, even though the API is, by default, based at the root.
// Since it is unlikely a user would put their API inside the /swagger path, we will
// special-case this scenario and remove that from the url. We will give the user an escape
// hatch via the preference if they do put their API under that path.
if (!preferences.GetBoolValue(WellKnownPreference.ConnectCommandSkipRootFix) &&
rootAddress.EndsWith(WebApiDefaultPathSuffix, StringComparison.OrdinalIgnoreCase))
{
rootAddress = rootAddress.Substring(0, rootAddress.Length - WebApiDefaultPathSuffix.Length);
}
apiConnection.RootUri = new Uri(rootAddress, UriKind.Absolute);
}

Expand Down
2 changes: 2 additions & 0 deletions src/Microsoft.HttpRepl/Preferences/WellKnownPreference.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,5 +177,7 @@ public static IReadOnlyList<string> Names
public static string UseDefaultCredentials { get; } = "httpClient.useDefaultCredentials";

public static string HttpClientUserAgent { get; } = "httpClient.userAgent";

public static string ConnectCommandSkipRootFix => "connectCommand.skipRootFix";
}
}
60 changes: 56 additions & 4 deletions test/Microsoft.HttpRepl.Tests/Commands/CommandTestsBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,43 @@ protected void ArrangeInputs(string commandText,
contentType);
}

protected void ArrangeInputsWithOptional(string commandText,
string baseAddress,
string path,
IDictionary<string, string> urlsWithResponse,
out MockedShellState shellState,
out HttpState httpState,
out ICoreParseResult parseResult,
ref MockedFileSystem fileSystem,
ref IPreferences preferences,
string header = "",
bool readBodyFromFile = false,
string fileContents = "",
string contentType = "")
{
parseResult = CoreParseResultHelper.Create(commandText);
shellState = new MockedShellState();

httpState = GetHttpStateWithOptional(ref fileSystem,
ref preferences,
baseAddress,
header,
path,
urlsWithResponse,
readBodyFromFile,
fileContents,
contentType);
}

protected static void VerifyErrorMessageWasWrittenToConsoleManagerError(IShellState shellState)
{
Mock<IWritable> error = Mock.Get(shellState.ConsoleManager.Error);

error.Verify(s => s.WriteLine(It.IsAny<string>()), Times.Once);
}

protected static HttpState GetHttpState(out MockedFileSystem fileSystem,
out IPreferences preferences,
protected static HttpState GetHttpStateWithOptional(ref MockedFileSystem fileSystem,
ref IPreferences preferences,
string baseAddress = "",
string header = "",
string path = "",
Expand All @@ -80,8 +108,8 @@ protected static HttpState GetHttpState(out MockedFileSystem fileSystem,
responseMessage.Content = new MockHttpContent(string.Empty);
MockHttpMessageHandler messageHandler = new MockHttpMessageHandler(urlsWithResponse, header, readFromFile, fileContents, contentType);
HttpClient httpClient = new HttpClient(messageHandler);
fileSystem = new MockedFileSystem();
preferences = new NullPreferences();
fileSystem ??= new MockedFileSystem();
preferences ??= new NullPreferences();

HttpState httpState = new HttpState(fileSystem, preferences, httpClient);

Expand All @@ -107,6 +135,30 @@ protected static HttpState GetHttpState(out MockedFileSystem fileSystem,
return httpState;
}

protected static HttpState GetHttpState(out MockedFileSystem fileSystem,
out IPreferences preferences,
string baseAddress = "",
string header = "",
string path = "",
IDictionary<string, string> urlsWithResponse = null,
bool readFromFile = false,
string fileContents = "",
string contentType = "")
{
fileSystem = new MockedFileSystem();
preferences = new NullPreferences();

return GetHttpStateWithOptional(ref fileSystem,
ref preferences,
baseAddress,
header,
path,
urlsWithResponse,
readFromFile,
fileContents,
contentType);
}

protected ICoreParseResult CreateCoreParseResult(string commandText)
{
return CoreParseResultHelper.Create(commandText);
Expand Down
79 changes: 79 additions & 0 deletions test/Microsoft.HttpRepl.Tests/Commands/ConnectCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using Microsoft.HttpRepl.Commands;
using Microsoft.HttpRepl.Fakes;
using Microsoft.HttpRepl.Preferences;
using Microsoft.HttpRepl.UserProfile;
using Microsoft.Repl.Parsing;
using Xunit;

Expand Down Expand Up @@ -632,6 +633,84 @@ public async Task ExecuteAsync_SwaggerOnlyWithBase_ShowsBaseAndSwaggerResult()
Assert.Contains(string.Format(Resources.Strings.ConnectCommand_Status_Swagger, httpState.SwaggerEndpoint), shellState.Output, StringComparer.Ordinal);
}

[Fact]
public async Task ExecuteAsync_RootWithSwaggerSuffix_FixesBase()
{
string rootAddress = "https://localhost:44368/swagger";
string expectedBaseAddress = "https://localhost:44368/";
string expectedSwaggerAddress = "https://localhost:44368/swagger/v1/swagger.json";
string swaggerContent = @"{
""openapi"": ""3.0.0"",
""info"": {
""title"": ""OpenAPI v3 Spec"",
""version"": ""v1""
},
""paths"": {
""/WeatherForecast"": {
}
}
}";

ArrangeInputs(commandText: $"connect {rootAddress}",
baseAddress: null,
path: null,
urlsWithResponse: new Dictionary<string, string>() { { expectedSwaggerAddress, swaggerContent } },
out MockedShellState shellState,
out HttpState httpState,
out ICoreParseResult parseResult,
out _,
out IPreferences preferences);

ConnectCommand connectCommand = new ConnectCommand(preferences);

await connectCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None);

Assert.Contains(string.Format(Resources.Strings.ConnectCommand_Status_Base, expectedBaseAddress), shellState.Output, StringComparer.Ordinal);
Assert.Contains(string.Format(Resources.Strings.ConnectCommand_Status_Swagger, expectedSwaggerAddress), shellState.Output, StringComparer.Ordinal);
}

[Fact]
public async Task ExecuteAsync_RootWithSwaggerSuffixAndOverride_DoesNotFixBase()
{
string rootAddress = "https://localhost:44368/swagger";
string expectedBaseAddress = rootAddress + "/";
string expectedSwaggerAddress = "https://localhost:44368/swagger/v1/swagger.json";
string swaggerContent = @"{
""openapi"": ""3.0.0"",
""info"": {
""title"": ""OpenAPI v3 Spec"",
""version"": ""v1""
},
""paths"": {
""/WeatherForecast"": {
}
}
}";

MockedFileSystem fileSystem = new MockedFileSystem();
UserProfileDirectoryProvider userProfileDirectoryProvider = new UserProfileDirectoryProvider();
IPreferences preferences = new UserFolderPreferences(fileSystem,
userProfileDirectoryProvider,
new Dictionary<string, string> { { WellKnownPreference.ConnectCommandSkipRootFix, "true"}});

ArrangeInputsWithOptional(commandText: $"connect {rootAddress}",
baseAddress: null,
path: null,
urlsWithResponse: new Dictionary<string, string>() { { expectedSwaggerAddress, swaggerContent } },
out MockedShellState shellState,
out HttpState httpState,
out ICoreParseResult parseResult,
ref fileSystem,
ref preferences);

ConnectCommand connectCommand = new ConnectCommand(preferences);

await connectCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None);

Assert.Contains(string.Format(Resources.Strings.ConnectCommand_Status_Base, expectedBaseAddress), shellState.Output, StringComparer.Ordinal);
Assert.Contains(string.Format(Resources.Strings.ConnectCommand_Status_Swagger, expectedSwaggerAddress), shellState.Output, StringComparer.Ordinal);
}

private void ArrangeInputs(string commandText, out MockedShellState shellState, out HttpState httpState, out ICoreParseResult parseResult, out IPreferences preferences, string fileContents = null)
{
ArrangeInputs(commandText,
Expand Down