Browse Source

Encode path parameter values in client proxies

pull/26261/head
maliming 1 month ago
parent
commit
2aecb6734e
No known key found for this signature in database GPG Key ID: A646B9CB645ECEA4
  1. 10
      framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyUrlBuilder.cs
  2. 1
      framework/test/Volo.Abp.Http.Client.Tests/Volo.Abp.Http.Client.Tests.csproj
  3. 200
      framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/ClientProxyUrlBuilder_PathParameter_Tests.cs
  4. 31
      framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/RegularTestControllerStaticClientProxy.cs
  5. 49
      framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/RegularTestControllerStaticClientProxy_Tests.cs
  6. 267
      framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/regular-test-generate-proxy.json
  7. 6
      framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/IRegularTestController.cs
  8. 21
      framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/RegularTestController.cs
  9. 36
      framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/RegularTestControllerClientProxy_Tests.cs

10
framework/src/Volo.Abp.Http.Client/Volo/Abp/Http/Client/ClientProxying/ClientProxyUrlBuilder.cs

@ -93,7 +93,7 @@ public class ClientProxyUrlBuilder : ITransientDependency
}
else if (pathParameter.DefaultValue != null)
{
urlBuilder = urlBuilder.Replace($"{{{pathParameter.Name}}}", await ConvertValueToStringAsync(pathParameter.DefaultValue));
urlBuilder = urlBuilder.Replace($"{{{pathParameter.Name}}}", EncodePathValue(await ConvertValueToStringAsync(pathParameter.DefaultValue)));
}
else
{
@ -124,11 +124,17 @@ public class ClientProxyUrlBuilder : ITransientDependency
}
}
urlBuilder = urlBuilder.Replace($"{{{pathParameter.Name}}}", await ConvertValueToStringAsync(value));
urlBuilder = urlBuilder.Replace($"{{{pathParameter.Name}}}", EncodePathValue(await ConvertValueToStringAsync(value)));
}
}
}
protected virtual string EncodePathValue(string value)
{
// Keep "/" unencoded so catch-all route parameters still receive multiple segments.
return string.Join("/", value.Split('/').Select(Uri.EscapeDataString));
}
protected virtual async Task AddQueryStringParametersAsync(StringBuilder urlBuilder, ActionApiDescriptionModel action, IReadOnlyDictionary<string, object?> methodArguments, ApiVersionInfo apiVersion)
{
var queryStringParameters = action.Parameters

1
framework/test/Volo.Abp.Http.Client.Tests/Volo.Abp.Http.Client.Tests.csproj

@ -16,6 +16,7 @@
<ItemGroup>
<EmbeddedResource Include="Volo\Abp\Http\Localization\en.json" />
<EmbeddedResource Include="Volo\Abp\Http\Client\ClientProxying\regular-test-generate-proxy.json" />
</ItemGroup>
</Project>

200
framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/ClientProxyUrlBuilder_PathParameter_Tests.cs

@ -0,0 +1,200 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Volo.Abp.Http.Modeling;
using Volo.Abp.Http.ProxyScripting.Generators;
using Volo.Abp.Timing;
using Xunit;
using MicrosoftOptions = Microsoft.Extensions.Options.Options;
namespace Volo.Abp.Http.Client.ClientProxying;
public class ClientProxyUrlBuilder_PathParameter_Tests
{
private readonly ClientProxyUrlBuilder _builder;
private static readonly ApiVersionInfo PathApiVersion = new("Path", "1.0");
public ClientProxyUrlBuilder_PathParameter_Tests()
{
_builder = CreateBuilder();
}
[Theory]
[InlineData("plain", "api/files/plain")]
[InlineData("a&b#c", "api/files/a%26b%23c")]
[InlineData("a?b=c", "api/files/a%3Fb%3Dc")]
[InlineData("a b", "api/files/a%20b")]
[InlineData("a%23b", "api/files/a%2523b")]
[InlineData("a/b#c", "api/files/a/b%23c")]
[InlineData("rvA-a&b#<q>", "api/files/rvA-a%26b%23%3Cq%3E")]
[InlineData("ä😀", "api/files/%C3%A4%F0%9F%98%80")]
public async Task Should_Encode_Path_Value(string value, string expectedUrl)
{
var action = BuildAction(PathParam("name"));
var url = await _builder.GenerateUrlWithParametersAsync(action, new Dictionary<string, object?> { ["name"] = value }, PathApiVersion);
url.ShouldBe(expectedUrl);
}
[Fact]
public async Task Should_Keep_Format_Of_Non_String_Path_Values()
{
var id = Guid.NewGuid();
(await GenerateUrlAsync(42)).ShouldBe("api/files/42");
(await GenerateUrlAsync(id)).ShouldBe($"api/files/{id}");
(await GenerateUrlAsync(true)).ShouldBe("api/files/True");
(await GenerateUrlAsync(DayOfWeek.Monday)).ShouldBe("api/files/Monday");
(await GenerateUrlAsync(new DateTime(2026, 10, 8, 12, 30, 45, DateTimeKind.Utc))).ShouldBe("api/files/2026-10-08T12%3A30%3A45.0000000Z");
}
[Fact]
public async Task Should_Keep_Empty_Path_Value_Empty()
{
(await GenerateUrlAsync(string.Empty)).ShouldBe("api/files/");
}
[Fact]
public async Task Should_Encode_Path_And_Query_Values_Separately()
{
var action = BuildAction("api/files/{name}", PathParam("name"), QueryParam("search"));
var url = await _builder.GenerateUrlWithParametersAsync(action, new Dictionary<string, object?> { ["name"] = "a b#c", ["search"] = "a b#c" }, PathApiVersion);
url.ShouldBe("api/files/a%20b%23c?search=a+b%23c");
}
[Fact]
public async Task Should_Replace_Path_Api_Version_And_Encode_Path_Value()
{
var action = BuildAction("api/v{apiVersion}/files/{name}", PathParam("apiVersion"), PathParam("name"));
var url = await _builder.GenerateUrlWithParametersAsync(action, new Dictionary<string, object?> { ["name"] = "a#b" }, new ApiVersionInfo("Path", "1.0"));
url.ShouldBe("api/v1.0/files/a%23b");
}
[Fact]
public async Task Should_Add_Query_Api_Version_After_Encoded_Path_Value()
{
var action = BuildAction(PathParam("name"));
var url = await _builder.GenerateUrlWithParametersAsync(action, new Dictionary<string, object?> { ["name"] = "a#b" }, new ApiVersionInfo("Query", "1.0"));
url.ShouldBe("api/files/a%23b?api-version=1.0");
}
[Fact]
public async Task Should_Not_Encode_Path_Converter_Result()
{
var builder = CreateBuilder(
services => services.AddTransient<PreEncodedPathValueToPath>(),
options => options.PathConverts.Add(typeof(PreEncodedPathValue), typeof(PreEncodedPathValueToPath)));
var action = BuildAction(PathParam("name"));
var url = await builder.GenerateUrlWithParametersAsync(action, new Dictionary<string, object?> { ["name"] = new PreEncodedPathValue("a%23b/c") }, PathApiVersion);
url.ShouldBe("api/files/a%23b/c");
}
[Fact]
public async Task Should_Encode_Default_Path_Value()
{
var action = BuildAction(PathParam("name", defaultValue: "a/b#c?d"));
var url = await _builder.GenerateUrlWithParametersAsync(action, new Dictionary<string, object?>(), PathApiVersion);
url.ShouldBe("api/files/a/b%23c%3Fd");
}
[Fact]
public async Task Should_Remove_Missing_Optional_Path_Value()
{
var action = BuildAction(PathParam("name", isOptional: true, defaultValue: "a#b"));
var url = await _builder.GenerateUrlWithParametersAsync(action, new Dictionary<string, object?>(), PathApiVersion);
url.ShouldBe("api/files/");
}
private Task<string> GenerateUrlAsync(object value)
{
return _builder.GenerateUrlWithParametersAsync(BuildAction(PathParam("name")), new Dictionary<string, object?> { ["name"] = value }, PathApiVersion);
}
private static ClientProxyUrlBuilder CreateBuilder(Action<IServiceCollection>? configureServices = null, Action<AbpHttpClientProxyingOptions>? configureOptions = null)
{
var services = new ServiceCollection();
configureServices?.Invoke(services);
var proxyingOptions = new AbpHttpClientProxyingOptions();
configureOptions?.Invoke(proxyingOptions);
var scopeFactory = services.BuildServiceProvider().GetRequiredService<IServiceScopeFactory>();
return new ClientProxyUrlBuilder(scopeFactory, MicrosoftOptions.Create(proxyingOptions), new TestClock());
}
private static ActionApiDescriptionModel BuildAction(ParameterApiDescriptionModel parameter)
{
return BuildAction("api/files/{" + parameter.Name + "}", parameter);
}
private static ActionApiDescriptionModel BuildAction(string url, params ParameterApiDescriptionModel[] parameters)
{
return new ActionApiDescriptionModel
{
UniqueName = "Sample",
Name = "Sample",
HttpMethod = "GET",
Url = url,
SupportedVersions = new List<string>(),
ParametersOnMethod = new List<MethodParameterApiDescriptionModel>(),
Parameters = new List<ParameterApiDescriptionModel>(parameters)
};
}
private static ParameterApiDescriptionModel PathParam(string name, bool isOptional = false, object? defaultValue = null)
{
return ParameterApiDescriptionModel.Create(
name,
jsonName: null,
nameOnMethod: name,
type: typeof(string),
isOptional: isOptional,
defaultValue: defaultValue,
bindingSourceId: ParameterBindingSources.Path);
}
private static ParameterApiDescriptionModel QueryParam(string name)
{
return ParameterApiDescriptionModel.Create(
name,
jsonName: null,
nameOnMethod: name,
type: typeof(string),
bindingSourceId: ParameterBindingSources.Query);
}
private record PreEncodedPathValue(string Value);
private class PreEncodedPathValueToPath : IObjectToPath<PreEncodedPathValue>
{
public Task<string> ConvertAsync(ActionApiDescriptionModel actionApiDescription, ParameterApiDescriptionModel parameterApiDescription, PreEncodedPathValue value)
{
return Task.FromResult(value.Value);
}
}
private class TestClock : IClock
{
public DateTime Now => DateTime.UtcNow;
public DateTimeKind Kind => DateTimeKind.Utc;
public bool SupportsMultipleTimezone => false;
public DateTime Normalize(DateTime dateTime) => dateTime;
public DateTime ConvertToUserTime(DateTime utcDateTime) => utcDateTime;
public DateTimeOffset ConvertToUserTime(DateTimeOffset dateTimeOffset) => dateTimeOffset;
public DateTime ConvertToUtc(DateTime dateTime) => dateTime;
}
}

31
framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/RegularTestControllerStaticClientProxy.cs

@ -0,0 +1,31 @@
using System.Threading.Tasks;
using Volo.Abp.Http.DynamicProxying;
namespace Volo.Abp.Http.Client.ClientProxying;
public class RegularTestControllerStaticClientProxy : ClientProxyBase<IRegularTestController>
{
public virtual async Task<string> GetWithStringPathAsync(string name)
{
return await RequestAsync<string>(nameof(GetWithStringPathAsync), new ClientProxyRequestTypeValue
{
{ typeof(string), name }
});
}
public virtual async Task<string> GetWithCatchAllPathAsync(string path)
{
return await RequestAsync<string>(nameof(GetWithCatchAllPathAsync), new ClientProxyRequestTypeValue
{
{ typeof(string), path }
});
}
public virtual async Task<string> GetWithSingleStarCatchAllPathAsync(string path)
{
return await RequestAsync<string>(nameof(GetWithSingleStarCatchAllPathAsync), new ClientProxyRequestTypeValue
{
{ typeof(string), path }
});
}
}

49
framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/RegularTestControllerStaticClientProxy_Tests.cs

@ -0,0 +1,49 @@
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Xunit;
namespace Volo.Abp.Http.Client.ClientProxying;
public class RegularTestControllerStaticClientProxy_Tests : AbpHttpClientTestBase
{
private readonly RegularTestControllerStaticClientProxy _proxy;
public RegularTestControllerStaticClientProxy_Tests()
{
_proxy = ServiceProvider.GetRequiredService<RegularTestControllerStaticClientProxy>();
}
[Theory]
[InlineData("plain")]
[InlineData("a&b#c")]
[InlineData("a?b=c")]
[InlineData("50% off")]
[InlineData("a+b")]
[InlineData("a%23b")]
[InlineData("rvA-a&b#<q>")]
[InlineData("ä😀")]
public async Task GetWithStringPathAsync(string name)
{
(await _proxy.GetWithStringPathAsync(name)).ShouldBe(name);
}
[Theory]
[InlineData("a")]
[InlineData("a/b")]
[InlineData("a/b#c?d")]
[InlineData("a b/c&d")]
public async Task GetWithCatchAllPathAsync(string path)
{
(await _proxy.GetWithCatchAllPathAsync(path)).ShouldBe(path);
}
[Theory]
[InlineData("a")]
[InlineData("a/b")]
[InlineData("a/b#c?d")]
public async Task GetWithSingleStarCatchAllPathAsync(string path)
{
(await _proxy.GetWithSingleStarCatchAllPathAsync(path)).ShouldBe(path);
}
}

267
framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/Client/ClientProxying/regular-test-generate-proxy.json

@ -0,0 +1,267 @@
{
"modules": {
"app": {
"rootPath": "app",
"remoteServiceName": "Default",
"controllers": {
"Volo.Abp.Http.DynamicProxying.RegularTestController": {
"controllerName": "RegularTest",
"controllerGroupName": "RegularTest",
"isRemoteService": true,
"isIntegrationService": false,
"apiVersion": null,
"type": "Volo.Abp.Http.DynamicProxying.RegularTestController",
"summary": null,
"remarks": null,
"description": null,
"displayName": null,
"interfaces": [
{
"type": "Volo.Abp.Http.DynamicProxying.IRegularTestController",
"name": "IRegularTestController",
"methods": [
{
"name": "GetWithStringPathAsync",
"parametersOnMethod": [
{
"name": "name",
"typeAsString": "System.String, System.Private.CoreLib",
"type": "System.String",
"typeSimple": "string",
"isOptional": false,
"defaultValue": null,
"summary": null,
"description": null,
"displayName": null
}
],
"returnValue": {
"type": "System.String",
"typeSimple": "string",
"summary": null,
"contentTypes": null,
"isRemoteStream": false
}
},
{
"name": "GetWithCatchAllPathAsync",
"parametersOnMethod": [
{
"name": "path",
"typeAsString": "System.String, System.Private.CoreLib",
"type": "System.String",
"typeSimple": "string",
"isOptional": false,
"defaultValue": null,
"summary": null,
"description": null,
"displayName": null
}
],
"returnValue": {
"type": "System.String",
"typeSimple": "string",
"summary": null,
"contentTypes": null,
"isRemoteStream": false
}
},
{
"name": "GetWithSingleStarCatchAllPathAsync",
"parametersOnMethod": [
{
"name": "path",
"typeAsString": "System.String, System.Private.CoreLib",
"type": "System.String",
"typeSimple": "string",
"isOptional": false,
"defaultValue": null,
"summary": null,
"description": null,
"displayName": null
}
],
"returnValue": {
"type": "System.String",
"typeSimple": "string",
"summary": null,
"contentTypes": null,
"isRemoteStream": false
}
}
]
}
],
"actions": {
"GetWithStringPathAsyncByName": {
"uniqueName": "GetWithStringPathAsyncByName",
"name": "GetWithStringPathAsync",
"httpMethod": "GET",
"url": "api/regular-test-controller/get-with-string-path/{name}",
"supportedVersions": [],
"parametersOnMethod": [
{
"name": "name",
"typeAsString": "System.String, System.Private.CoreLib",
"type": "System.String",
"typeSimple": "string",
"isOptional": false,
"defaultValue": null,
"summary": null,
"description": null,
"displayName": null
}
],
"parameters": [
{
"nameOnMethod": "name",
"name": "name",
"jsonName": null,
"type": "System.String",
"typeSimple": "string",
"isOptional": false,
"defaultValue": null,
"constraintTypes": [],
"bindingSourceId": "Path",
"descriptorName": "",
"summary": null,
"description": null,
"displayName": null
}
],
"returnValue": {
"type": "System.String",
"typeSimple": "string",
"summary": null,
"contentTypes": [
"text/plain",
"application/json",
"text/json"
],
"isRemoteStream": false
},
"allowAnonymous": null,
"authorizeDatas": [],
"implementFrom": "Volo.Abp.Http.DynamicProxying.IRegularTestController",
"summary": null,
"remarks": null,
"description": null,
"displayName": null
},
"GetWithCatchAllPathAsyncByPath": {
"uniqueName": "GetWithCatchAllPathAsyncByPath",
"name": "GetWithCatchAllPathAsync",
"httpMethod": "GET",
"url": "api/regular-test-controller/get-with-catch-all-path/{path}",
"supportedVersions": [],
"parametersOnMethod": [
{
"name": "path",
"typeAsString": "System.String, System.Private.CoreLib",
"type": "System.String",
"typeSimple": "string",
"isOptional": false,
"defaultValue": null,
"summary": null,
"description": null,
"displayName": null
}
],
"parameters": [
{
"nameOnMethod": "path",
"name": "path",
"jsonName": null,
"type": "System.String",
"typeSimple": "string",
"isOptional": false,
"defaultValue": null,
"constraintTypes": [],
"bindingSourceId": "Path",
"descriptorName": "",
"summary": null,
"description": null,
"displayName": null
}
],
"returnValue": {
"type": "System.String",
"typeSimple": "string",
"summary": null,
"contentTypes": [
"text/plain",
"application/json",
"text/json"
],
"isRemoteStream": false
},
"allowAnonymous": null,
"authorizeDatas": [],
"implementFrom": "Volo.Abp.Http.DynamicProxying.IRegularTestController",
"summary": null,
"remarks": null,
"description": null,
"displayName": null
},
"GetWithSingleStarCatchAllPathAsyncByPath": {
"uniqueName": "GetWithSingleStarCatchAllPathAsyncByPath",
"name": "GetWithSingleStarCatchAllPathAsync",
"httpMethod": "GET",
"url": "api/regular-test-controller/get-with-single-star-catch-all-path/{path}",
"supportedVersions": [],
"parametersOnMethod": [
{
"name": "path",
"typeAsString": "System.String, System.Private.CoreLib",
"type": "System.String",
"typeSimple": "string",
"isOptional": false,
"defaultValue": null,
"summary": null,
"description": null,
"displayName": null
}
],
"parameters": [
{
"nameOnMethod": "path",
"name": "path",
"jsonName": null,
"type": "System.String",
"typeSimple": "string",
"isOptional": false,
"defaultValue": null,
"constraintTypes": [],
"bindingSourceId": "Path",
"descriptorName": "",
"summary": null,
"description": null,
"displayName": null
}
],
"returnValue": {
"type": "System.String",
"typeSimple": "string",
"summary": null,
"contentTypes": [
"text/plain",
"application/json",
"text/json"
],
"isRemoteStream": false
},
"allowAnonymous": null,
"authorizeDatas": [],
"implementFrom": "Volo.Abp.Http.DynamicProxying.IRegularTestController",
"summary": null,
"remarks": null,
"description": null,
"displayName": null
}
}
}
}
}
},
"types": {}
}

6
framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/IRegularTestController.cs

@ -55,6 +55,12 @@ public interface IRegularTestController
Task<Car> GetObjectAndIdWithQueryAsync(int id, Car bodyValue);
Task<string> GetWithStringPathAsync(string name);
Task<string> GetWithCatchAllPathAsync(string path);
Task<string> GetWithSingleStarCatchAllPathAsync(string path);
Task<string> PutValueWithBodyAsync(string bodyValue);
Task<string> PatchValueWithBodyAsync(string bodyValue);

21
framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/RegularTestController.cs

@ -196,6 +196,27 @@ public class RegularTestController : AbpController, IRegularTestController
return Task.FromResult(bodyValue);
}
[HttpGet]
[Route("get-with-string-path/{name}")]
public Task<string> GetWithStringPathAsync(string name)
{
return Task.FromResult(name);
}
[HttpGet]
[Route("get-with-catch-all-path/{**path}")]
public Task<string> GetWithCatchAllPathAsync(string path)
{
return Task.FromResult(path);
}
[HttpGet]
[Route("get-with-single-star-catch-all-path/{*path}")]
public Task<string> GetWithSingleStarCatchAllPathAsync(string path)
{
return Task.FromResult(path);
}
[HttpPut]
[Route("put-with-body")]
public Task<string> PutValueWithBodyAsync([FromBody] string bodyValue)

36
framework/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/RegularTestControllerClientProxy_Tests.cs

@ -157,6 +157,42 @@ public class RegularTestControllerClientProxy_Tests : AbpHttpClientTestBase
result.Model.ShouldBe("Ford");
}
[Theory]
[InlineData("plain")]
[InlineData("a&b#c")]
[InlineData("a?b=c")]
[InlineData("50% off")]
[InlineData("a+b")]
[InlineData("a%23b")]
[InlineData("rvA-a&b#<q>")]
[InlineData("ä😀")]
public async Task GetWithStringPathAsync(string name)
{
var result = await _controller.GetWithStringPathAsync(name);
result.ShouldBe(name);
}
[Theory]
[InlineData("a")]
[InlineData("a/b")]
[InlineData("a/b#c?d")]
[InlineData("a b/c&d")]
public async Task GetWithCatchAllPathAsync(string path)
{
var result = await _controller.GetWithCatchAllPathAsync(path);
result.ShouldBe(path);
}
[Theory]
[InlineData("a")]
[InlineData("a/b")]
[InlineData("a/b#c?d")]
public async Task GetWithSingleStarCatchAllPathAsync(string path)
{
var result = await _controller.GetWithSingleStarCatchAllPathAsync(path);
result.ShouldBe(path);
}
[Fact]
public async Task PatchValueWithBodyAsync()
{

Loading…
Cancel
Save