简体   繁体   English

在获取请求中传递json params

[英]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. 但是在Query实例上重新调用会调用ToString而不是使用序列化程序。 Is there any way to achieve this without using a wrapper class? 有没有办法在不使用包装类的情况下实现这一目的?

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

I ended up using a custom serializer which converts to JSON every type except primitive types and those implementing IConvertible: 我最终使用了一个自定义序列化程序,除了基本类型和实现IConvertible的那些类型之外,每个类型都会转换为JSON:

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

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

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