问题描述
我将Refit用于RestAPI。
我需要创建相同的查询字符串 api / item?c [] = 14& c [] = 74
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);
并创建CustomParameterFormatter
And create CustomParameterFormatter
string query = string.Join("&c[]=", values);
CustomParameterFormatter生成的字符串 14& c [] = 74
CustomParameterFormatter generated string 14&c[]=74
但是要调整编码参数并生成url api / item?c%5B%5D = 14%26c%5B%5D%3D74
But Refit encoded parameter and generated url api/item?c%5B%5D=14%26c%5B%5D%3D74
如何禁用此功能?
推荐答案
首先您的api服务器能够解析以下内容吗?
api / item?c%5B%5D = 14%26c%5B%5D%3D74
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.
这是对 Refit 的看法,即应该对uris进行编码,
This is something Refit is a bit opinionated about, i.e uris should be encoded, the server should be upgraded to read encoded uris.
但这显然应该是 Refit 中的选择设置,但事实并非如此。
But this clearly should be a opt-in settings in Refit but it´s not.
因此,您目前可以使用DelegatingHandler来做到这一点:
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()))
这篇关于如何在Refit中禁用urlencoding get-params?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!