6

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?

Mark Toman
  • 3,090
  • 2
  • 17
  • 18
  • I had the same problem with ReFit (it is not offering you to change how stuff in the url is serialized) and decided to roll my own ReFit like project. As long as your code is not supposed to be downloaded from windows store or something, you can use WebAnchor which will let you decide how to serialize your query-object. – Mattias Nordqvist Jan 18 '16 at 14:50
  • @mattias kudos for WebAnchor, however you can use a custom query serializer with Refit – Mark Toman Feb 24 '16 at 13:50
  • allright, that's news to me. :) nice – Mattias Nordqvist Feb 24 '16 at 15:53

2 Answers2

1

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
Eris
  • 7,378
  • 1
  • 30
  • 45
1

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()
};
Mark Toman
  • 3,090
  • 2
  • 17
  • 18