How to set timeout in Refit library

一世执手 提交于 2019-12-04 08:21:19

The accepted answer is the correct way to enforce a timeout for a single request, but if you want to have a single consistent timeout value for all requests, you can pass a preconfigured HttpClient with its Timeout property set:

var api = RestService.For<IDevice>(new HttpClient 
{
    BaseAddress = new Uri("http://localhost"),
    Timeout = TimeSpan.FromSeconds(10)
});

Here is an example project.

I finally found a way of setting the timeout for a request in Refit. I used CancelationToken. Here is the modified code after adding CancelationToken

Interface:

interface IDevice
{
  [Get("/app/device/{id}")]
  Task<Device> GetDevice(string id, [Header("Authorization")] string authorization, CancellationToken cancellationToken);
}

Invoking the API:

var device = RestService.For<IDevice>("http://localhost");    
CancellationTokenSource tokenSource = new CancellationTokenSource();
tokenSource.CancelAfter(10000); // 10000 ms
CancellationToken token = tokenSource.Token;          
var dev = await device.GetDevice("15e2a691-06df-4741-b26e-87e1eecc6bd7", "Bearer OAUTH_TOKEN", token);

It works properly for me. I don't know whether it is the proper way or not. If it is a wrong, kindly suggest the correct way.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!