RestSharp更新AddHandler方法的使用以使用工厂委托

时间:2019-03-05 23:09:10

标签: c# restsharp

RestSharp v106.6.9的最新版本显然进行了一些更改,使得对Request的AddHandler方法的覆盖已过时,例如以下签名:

[Obsolete("Use the overload that accepts a factory delegate")]
public void AddHandler(IDeserializer deserializer, params string[] contentTypes)

建议使用facrory委托表格

public void AddHandler(string contentType, Func<IDeserializer> deserializerFactory)

public void AddHandler(Func<IDeserializer> deserializerFactory, params string[] contentTypes)

任何人都可以向我指出实现此目标的示例。 或解释如何将下面实现IDeserializer的customSerializer的使用转换为工厂委托:

RestClient.AddHandler("application/json", CustomJsonSerializer.Instance);


public class CustomJsonSerializer : IDeserializer
{
    public static CustomJsonSerializer Instance => new CustomJsonSerializer();

    public string ContentType
    {
        get => "application/json";
        set { } // maybe used for Serialization?
    }

    public string DateFormat { get; set; }

    public string Namespace { get; set; }

    public string RootElement { get; set; }

    public T Deserialize<T>(IRestResponse response) => RestSharpResponseHandlers.DeserializeObject<T>(response);
}

2 个答案:

答案 0 :(得分:4)

根据https://github.com/restsharp/RestSharp/blob/master/RestSharp/RestClient.cs上的源代码:

 [Obsolete("Use the overload that accepts a factory delegate")]
 public void AddHandler(string contentType, IDeserializer deserializer) =>
    AddHandler(contentType, () => deserializer);

过时的重载仅调用AddHandler(string contentType, Func<IDeserializer> deserializerFactory)重载。

因此,您可以替换代码以添加自定义处理程序,如下所示:

RestClient.AddHandler("application/json", () => { return CustomJsonSerializer.Instance; });

答案 1 :(得分:0)

我遇到了同样的问题。看起来OpenAPI代码正在为多种上下文类型设置多个处理程序,所以我写了这个小函数

        private void AddHandlerHelper(RestClient client, IDeserializer deserializerFactory, string[] contextTypes)
        {
            foreach( var contextType in contextTypes)
            client.AddHandler(contextType,() => deserializerFactory);
        }

呼叫从此更改:

client.AddHandler(() => existingDeserializer, "application/json", "text/json", "text/x-json", "text/javascript", "*+json");

对此

AddHandlerHelper(client, existingDeserializer, new string[] { "application/json", "text/json", "text/x-json", "text/javascript", "*+json"});

在生成的代码中我需要该功能有六个位置。