| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="HttpRequestExtensions.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Net.Http; |
| | | 9 | | |
| | | 10 | | #pragma warning disable IDE0130 // Namespace does not match folder structure |
| | | 11 | | namespace MyNet.Http; |
| | | 12 | | #pragma warning restore IDE0130 // Namespace does not match folder structure |
| | | 13 | | |
| | | 14 | | public static class HttpRequestExtensions |
| | | 15 | | { |
| | | 16 | | private const string TimeoutPropertyKey = "RequestTimeout"; |
| | | 17 | | |
| | | 18 | | extension(HttpRequestMessage request) |
| | | 19 | | { |
| | | 20 | | /// <summary> |
| | | 21 | | /// Sets a timeout for the HTTP request by storing it in the request's options. This allows for per-request time |
| | | 22 | | /// </summary> |
| | | 23 | | /// <param name="timeout">The timeout duration for the request.</param> |
| | | 24 | | /// <exception cref="ArgumentNullException">Thrown if the request is null.</exception> |
| | | 25 | | public void SetTimeout(TimeSpan? timeout) |
| | | 26 | | { |
| | 6 | 27 | | ArgumentNullException.ThrowIfNull(request); |
| | | 28 | | |
| | 3 | 29 | | request.Options.Set(new HttpRequestOptionsKey<TimeSpan?>(TimeoutPropertyKey), timeout); |
| | 3 | 30 | | } |
| | | 31 | | |
| | | 32 | | /// <summary> |
| | | 33 | | /// Retrieves the timeout value for the HTTP request from its options. If no timeout is set, it returns null. Th |
| | | 34 | | /// </summary> |
| | | 35 | | /// <returns>The timeout duration for the request, or null if no timeout is set.</returns> |
| | | 36 | | /// <exception cref="ArgumentNullException">Thrown if the request is null.</exception> |
| | | 37 | | public TimeSpan? GetTimeout() |
| | | 38 | | { |
| | 21 | 39 | | ArgumentNullException.ThrowIfNull(request); |
| | | 40 | | |
| | 21 | 41 | | return request.Options.TryGetValue(new HttpRequestOptionsKey<TimeSpan?>(TimeoutPropertyKey), out var value) |
| | | 42 | | } |
| | | 43 | | } |
| | | 44 | | } |
| | | 45 | | |