Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable urlencoding get-params in Refit?

Tags:

c#

.net

uwp

refit

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?

like image 985
Make Makeluv Avatar asked Nov 16 '16 13:11

Make Makeluv


2 Answers

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()))
like image 123
Ahmed Alejo Avatar answered Oct 01 '22 16:10

Ahmed Alejo


For anyone who stumbles across this old question you can use [QueryUriFormat(UriFormat.Unescaped)] attribute.

like image 24
mmoon Avatar answered Oct 01 '22 17:10

mmoon