Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[release/8.0] Encode query parameters for AutoClient #4437

Merged
merged 1 commit into from
Sep 18, 2023
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
11 changes: 9 additions & 2 deletions src/Generators/Microsoft.Gen.AutoClient/Emitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -231,18 +231,25 @@ private void GenRestApiMethod(RestApiMethod restApiMethod, RestApiType restApiTy
var firstQuery = true;
foreach (var param in restApiMethod.AllParameters.Where(m => m.IsQuery))
{
var escapedParamName = $"{param.Name}Escaped";

// Use interpolated string to handle any null values from any type like nullable value types or reference types.
OutLn($"var {escapedParamName} = {Uri}.EscapeDataString($\"{{{param.Name}}}\");");

if (firstQuery)
{
_ = pathSb.Append($"?{param.QueryKey}={{{param.Name}}}");
_ = pathSb.Append($"?{param.QueryKey}={{{escapedParamName}}}");
}
else
{
_ = pathSb.Append($"&{param.QueryKey}={{{param.Name}}}");
_ = pathSb.Append($"&{param.QueryKey}={{{escapedParamName}}}");
}

firstQuery = false;
}

OutLn();

var definePath = restApiMethod.FormatParameters.Count > 0 || !firstQuery;
var body = restApiMethod.AllParameters.FirstOrDefault(m => m.IsBody);

Expand Down
21 changes: 21 additions & 0 deletions test/Generators/Microsoft.Gen.AutoClient/Generated/QueryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,27 @@ public async Task QueryFromParameter()
Assert.Equal("Success!", response);
}

[Fact]
public async Task QueryIsEscaped()
{
_handlerMock
.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.Is<HttpRequestMessage>(message =>
message.Method == HttpMethod.Get &&
message.RequestUri != null &&
message.RequestUri.PathAndQuery == "/api/users?paramQuery=http%3A%2F%2Fmicrosoft.com"),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("Success!")
});

var response = await _sut.GetUsers("http://microsoft.com");

Assert.Equal("Success!", response);
}

[Fact]
public async Task QueryFromParameterCustom()
{
Expand Down