I use Refit for RestAPI.
I need create query strings same api/item?c[]=14&c[]=74
In refit interface I created method
[Get("/item")]
Task<TendersResponse> GetTenders([AliasAs("c")]List<string> categories=null);
And create CustomParameterFormatter
string query = string.Join("&c[]=", values);
CustomParameterFormatter generated string 14&c[]=74
But Refit encoded parameter and generated url api/item?c%5B%5D=14%26c%5B%5D%3D74
How disable this feature?
First of all was your api server able to parse the follow?
api/item?c%5B%5D=14%26c%5B%5D%3D74
Encoding is great for avoiding code injection to your server.
This is something Refit is a bit opinionated about, i.e uris should be encoded, the server should be upgraded to read encoded uris.
But this clearly should be a opt-in settings in Refit but it´s not.
So you can currently can do that by using a DelegatingHandler:
/// <summary>
/// Makes sure the query string of an <see cref="System.Uri"/>
/// </summary>
public class UriQueryUnescapingHandler : DelegatingHandler
{
public UriQueryUnescapingHandler()
: base(new HttpClientHandler()) { }
public UriQueryUnescapingHandler(HttpMessageHandler innerHandler)
: base(innerHandler)
{ }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var uri = request.RequestUri;
//You could also simply unescape the whole uri.OriginalString
//but i don´t recommend that, i.e only fix what´s broken
var unescapedQuery = Uri.UnescapeDataString(uri.Query);
var userInfo = string.IsNullOrWhiteSpace(uri.UserInfo) ? "" : $"{uri.UserInfo}@";
var scheme = string.IsNullOrWhiteSpace(uri.Scheme) ? "" : $"{uri.Scheme}://";
request.RequestUri = new Uri($"{scheme}{userInfo}{uri.Authority}{uri.AbsolutePath}{unescapedQuery}{uri.Fragment}");
return base.SendAsync(request, cancellationToken);
}
}
Refit.RestService.For<IYourService>(new HttpClient(new UriQueryUnescapingHandler()))
For anyone who stumbles across this old question you can use [QueryUriFormat(UriFormat.Unescaped)] attribute.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With