问题
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?
回答1:
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()))
来源:https://stackoverflow.com/questions/40632827/how-to-disable-urlencoding-get-params-in-refit