Skip to content

Commit

Permalink
Encode query parameters for AutoClient (#4437)
Browse files Browse the repository at this point in the history
Co-authored-by: Sebastien Ros <sebastienros@gmail.com>
  • Loading branch information
github-actions[bot] and sebastienros authored Sep 18, 2023
1 parent 124514d commit 6edde33
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
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 @@ -232,18 +232,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

0 comments on commit 6edde33

Please sign in to comment.