Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass json params in get requests

Tags:

c#

.net

refit

I have:

public class Query {...}
public interface IClient
{
    [Get("/api/endpoint?data={query}")]
    Task<Result> GetData(Query query);
}

but Refit on the Query instance calls ToString instead of using the serializer. Is there any way to achieve this without using a wrapper class?

like image 240
Marek Toman Avatar asked Nov 21 '15 15:11

Marek Toman


People also ask

Can you pass JSON in a GET request?

To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode).

Can we pass parameters in JSON file?

The transfer of parameters to the script can be done either directly or through a JSON or CSV file.


2 Answers

If I understand the docs correctly, the only issue is the naming. Since you are using it as a param instead of a part of the path, it would be closer to this:

public class Query {...}
public interface IClient
{
    [Get("/api/endpoint")]
    Task<Result> GetData(Query data);
}

Then call it as you normally would:

GetData(aQueryObject);

or

http://myhost/api/endpoint?data=somestuff
like image 182
Eris Avatar answered Oct 31 '22 11:10

Eris


I ended up using a custom serializer which converts to JSON every type except primitive types and those implementing IConvertible:

class DefaultUrlParameterFormatter : IUrlParameterFormatter
{
    public string Format(object value, ParameterInfo parameterInfo)
    {
        if (value == null)
            return null;

        if (parameterInfo.ParameterType.IsPrimitive)
            return value.ToString();

        var convertible = value as IConvertible; //e.g. string, DateTime
        if (convertible != null)
            return convertible.ToString();

        return JsonConvert.SerializeObject(value);
    }
}

var settings = new RefitSettings
{
    UrlParameterFormatter = new DefaultUrlParameterFormatter()
};
like image 45
Marek Toman Avatar answered Oct 31 '22 12:10

Marek Toman