实施WebRequest重试

时间:2018-06-20 14:53:24

标签: c# .net webrequest

我有一项服务,可以将很多数据从Bungie API下载到SQL数据库。我遇到的问题是,他们的服务器每隔一段时间就会响应504错误。我想知道是否有人对响应失败后如何重试WebRequest代码有任何有用的建议。这是我现在正在做的事情:

    private async Task<T> Deserialize<T>(Stream stream)
    {
        using (var reader = new StreamReader(stream))
        {
            var json = await reader.ReadToEndAsync();
            return Deserialize<T>(json);
        }
    }

    private T Deserialize<T>(string json)
    {
        return JsonConvert.DeserializeObject<T>(json);
    }

    private Task<WebRequest> Request(object service, string methodName, object model)
    {
        var requestBuilder = new RequestBuilder();
        requestBuilder.AddHeaders(Headers);
        return requestBuilder.Build(service, methodName, model);
    }

    protected virtual Task<WebResponse> Response(WebRequest request)
    {
        return request.GetResponseAsync();
    }

    public async Task<T> Request<T>(object service, string methodName, object model = null)
    {
        var request = await Request(service, methodName, model);
        WebResponse response = await Response(request);
        return await Deserialize<T>(response.GetResponseStream());
    }

发生错误时,行WebResponse response = await Response(request);返回null。

0 个答案:

没有答案