简体   繁体   中英

C# GetResponse() How to timeout dynamically created url?

This is my method, to which I am passing the url to check if it's active. The link is being activated on the wowza service so it takes some time until it's "alive"

GetResponse is returning the 404 Error because the url is not reached.

Is there a way to get the timeout instead of 404 error if the url is not alive after specified time?

public async Task<IActionResult> GetLinkIsAlive([FromQuery] string url, [FromQuery] int timeout)
{
    HttpWebResponse webResponse;
    try
    {
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Timeout = timeout;
        webRequest.Method = "GET";
        webResponse = webRequest.GetResponse() as HttpWebResponse;
        return Ok(webResponse.StatusCode);
    }
    catch (WebException ex)
    {
        return BadRequest(ex.Message);
    }
}

You can use connection pooling.
It's using IHttpClientFactory that helps to maintain the pooling and lifetime of clients

In your startup class:

   services.AddHttpClient<NameofyourService, NameofyourService>()
              .AddTransientHttpErrorPolicy(  
        p => p.WaitAndRetryAsync(new[]
        {
            TimeSpan.FromSeconds(1),
            TimeSpan.FromSeconds(5),
            TimeSpan.FromSeconds(10)
        }));

It requires Microsoft.Extensions.Http.Polly You need to use HttpClient for your service. All added configurations will apply automatically.

My solution to this was calling the link in the while loop every 1s and await the whole Task.

private async Task<bool> IsLiveStreamAlive(string streamUrl, int retriesCount = 30)
{
    try
    {
        bool res = false;
        HttpClient client = new HttpClient();
        Uri uri = new Uri(streamUrl);
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri);
        var request = new HttpRequestMessage(HttpMethod.Get, uri);
        while (retriesCount > 1)
        {
            await Task.Delay(1000);
            retriesCount--;
            HttpResponseMessage httpResponse = await client.GetAsync(uri);
            res = httpResponse.StatusCode == HttpStatusCode.OK ? true : false;
            if (res)
            {
                Log.Info(string.Format("Stream alive: {0}", streamUrl));
                break;
            }
        }
        return res;
    }
    catch (WebException ex)
    {
        Log.Error(ex);               
    }
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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