简体   繁体   English

如何在Refit中禁用urlencoding get-params?

[英]How to disable urlencoding get-params in Refit?

I use Refit for RestAPI. 我将Refit用于RestAPI。 I need create query strings same api/item?c[]=14&c[]=74 我需要创建查询字符串相同的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 并创建CustomParameterFormatter

string query = string.Join("&c[]=", values);

CustomParameterFormatter generated string 14&c[]=74 CustomParameterFormatter生成的字符串14&c[]=74

But Refit encoded parameter and generated url api/item?c%5B%5D=14%26c%5B%5D%3D74 但是重新编码参数并生成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服务器是否能够解析以下内容? 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, ie uris should be encoded, the server should be upgraded to read encoded uris. 这是Refit有点自以为是的事情,即应该对uris进行编码,应该将服务器升级为读取已编码的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: 因此,您目前可以使用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()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM