Search code examples
c#.netrefit

Pass json params in get requests


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?


Solution

  • 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()
    };