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

WebAPI: Treat the args dictionary as immutable #995

Merged
merged 4 commits into from
Jun 14, 2021
Merged
Show file tree
Hide file tree
Changes from 3 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
77 changes: 35 additions & 42 deletions SteamKit2/SteamKit2/Steam/WebAPI/WebAPI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -222,68 +222,61 @@ public async Task<KeyValue> CallAsync( HttpMethod method, string func, int versi
throw new ArgumentNullException( nameof(func) );
}

if ( args == null )
if ( args != null && args.TryGetValue( "format", out var format ) )
{
args = new Dictionary<string, object>();
if ( !( format is string formatText ) || formatText != "vdf" )
{
throw new ArgumentException( $"{nameof( args )} include unsupported {nameof( format )}: {format}" );
}
}


var urlBuilder = new StringBuilder();
var paramBuilder = new StringBuilder();
Copy link
Member

@xPaw xPaw Jun 13, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is HttpValueCollection only in ASP? If .NET's uri/querystring stuff can be used, all this custom escaping code could be removed.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems to be an internal class only in both .NET Framework and Core, and does not appear as an available API anywhere on MS docs site. HttpUtility can parse but not build. FormUrlEncoded content can build but it requires having a full IEnumerable of all the values upfront, and is async.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's lame.


urlBuilder.AppendFormat( "{0}/{1}/v{2}", iface, func, version );
var paramsGoInQueryString = HttpMethod.Get.Equals( method );

var isGet = HttpMethod.Get.Equals( method );
var urlBuilder = paramsGoInQueryString ? paramBuilder : new StringBuilder();
urlBuilder.AppendFormat( "{0}/{1}/v{2}", iface, func, version );

if ( isGet )
if (paramsGoInQueryString)
{
// if we're doing a GET request, we'll build the params onto the url
paramBuilder = urlBuilder;
paramBuilder.Append( "/?" ); // start our GET params
urlBuilder.Append( "/?" );
}

if ( args.TryGetValue( "format", out var format ) )
{
if ( !(format is string formatText) || formatText != "vdf" )
{
throw new ArgumentException( $"{nameof(args)} include unsupported {nameof(format)}: {format}" );
}
}
else
if ( !string.IsNullOrEmpty( apiKey ) && args != null && !args.ContainsKey( "key" ) )
{
args.Add( "format", "vdf" );
paramBuilder.Append( "key=" );
paramBuilder.Append( Uri.EscapeDataString( apiKey ) );
}

if ( !string.IsNullOrEmpty( apiKey ) && !args.ContainsKey( "key" ) )
{
args.Add( "key", apiKey );
}
paramBuilder.Append( "format=vdf" );

// append any args
paramBuilder.Append( string.Join( "&", args.Select( kvp =>
if ( args != null )
{
string key = HttpUtility.UrlEncode( kvp.Key );
string value;

if ( kvp.Value == null )
{
value = string.Empty;
}
else if ( kvp.Value is byte[] buffer )
foreach ( var (key, value) in args )
{
value = HttpUtility.UrlEncode( buffer );
}
else
{
value = HttpUtility.UrlEncode( kvp.Value.ToString() );
}
paramBuilder.Append( '&' );
paramBuilder.Append( Uri.EscapeDataString( key ) );
paramBuilder.Append( '=' );

return string.Format( "{0}={1}", key, value );
} ) ) );
switch ( value )
{
case null:
break;

case byte[] byteArrayValue:
paramBuilder.Append( HttpUtility.UrlEncode( byteArrayValue ) );
break;

default:
paramBuilder.Append( Uri.EscapeDataString( value.ToString() ) );
break;
}
}
}

var request = new HttpRequestMessage( method, urlBuilder.ToString() );

if ( !isGet )
if ( !paramsGoInQueryString )
{
request.Content = new StringContent( paramBuilder.ToString() );
request.Content.Headers.ContentType = new MediaTypeHeaderValue( "application/x-www-form-urlencoded" );
Expand Down
49 changes: 49 additions & 0 deletions SteamKit2/Tests/WebAPIFacts.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,55 @@ public async Task DoesntThrowOnArgumentsReuse()
await iface.CallAsync( HttpMethod.Get, "GetFoo", args: args );
}

[Fact]
public async Task UsesArgsAsQueryStringParams()
{
var capturingHandler = new CaturingHttpMessageHandler();
var configuration = SteamConfiguration.Create( c => c.WithHttpClientFactory( () => new HttpClient( capturingHandler ) ) );

dynamic iface = configuration.GetAsyncWebAPIInterface( "IFooService" );

var args = new Dictionary<string, object>
{
[ "f" ] = "foo",
[ "b" ] = "bar",
};

var response = await iface.PerformFooOperation2( args );

var request = capturingHandler.MostRecentRequest;
Assert.NotNull( request );
Assert.Equal( HttpMethod.Get, request.Method );
Assert.Equal( "/IFooService/PerformFooOperation/v2/", request.RequestUri.AbsolutePath );

var values = request.RequestUri.ParseQueryString();
Assert.Equal( 3, values.Count );
Assert.Equal( "foo", values[ "f" ] );
Assert.Equal( "bar", values[ "b" ] );
Assert.Equal( "vdf", values[ "format" ] );
}

[Fact]
public async Task SupportsNullArgsDictionary()
{
var capturingHandler = new CaturingHttpMessageHandler();
var configuration = SteamConfiguration.Create( c => c.WithHttpClientFactory( () => new HttpClient( capturingHandler ) ) );

dynamic iface = configuration.GetAsyncWebAPIInterface( "IFooService" );

var args = default( Dictionary<string, object> );
var response = await iface.CallAsync( HttpMethod.Get, "PerformFooOperation", 2, args );

var request = capturingHandler.MostRecentRequest;
Assert.NotNull( request );
Assert.Equal( HttpMethod.Get, request.Method );
Assert.Equal( "/IFooService/PerformFooOperation/v2/", request.RequestUri.AbsolutePath );

var values = request.RequestUri.ParseQueryString();
Assert.Single( values);
Assert.Equal( "vdf", values[ "format" ] );
}

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