private HttpServerCacheHeaders BuildHeaders( bool cacheControlIsNull = false, bool privateCache = false, bool noStore = false, bool immutable = false, TimeSpan?maxAge = null, TimeSpan?sMaxAge = null, FSharpOption <string> pragma = null, FSharpOption <EntityTagHeaderValue> eTag = null, FSharpOption <DateTime> exipiresUtc = null, FSharpOption <DateTime> lasModifiedUtc = null, FSharpOption <string> vary = null) { CacheControlHeaderValue cacheControl = null; if (!cacheControlIsNull) { cacheControl = immutable ? CacheControlHeaderValue.Parse("immutable") : new CacheControlHeaderValue(); cacheControl.NoStore = noStore; cacheControl.MaxAge = maxAge; cacheControl.SharedMaxAge = sMaxAge; cacheControl.Private = privateCache; } return(new HttpServerCacheHeaders( cacheControl ?? FSharpOption <CacheControlHeaderValue> .None, pragma ?? FSharpOption <string> .None, eTag ?? FSharpOption <EntityTagHeaderValue> .None, exipiresUtc ?? FSharpOption <DateTime> .None, lasModifiedUtc ?? FSharpOption <DateTime> .None, vary ?? FSharpOption <string> .None)); }
public static async Task AddStorageAsync(this MockServerHttpClientHandler handler, IStorage storage) { var files = (await storage.ListAsync(CancellationToken.None)).Select(x => x.Uri); foreach (var file in files) { var storageFileUrl = file; var relativeFileUrl = "/" + storageFileUrl.ToString().Replace(storage.BaseAddress.ToString(), string.Empty); handler.SetAction(relativeFileUrl, async message => { var content = await storage.LoadAsync(storageFileUrl, CancellationToken.None); var response = new HttpResponseMessage(HttpStatusCode.OK); if (!string.IsNullOrEmpty(content.CacheControl)) { response.Headers.CacheControl = CacheControlHeaderValue.Parse(content.CacheControl); } response.Content = new StreamContent(content.GetContentStream()); if (!string.IsNullOrEmpty(content.ContentType)) { response.Content.Headers.ContentType = new MediaTypeHeaderValue(content.ContentType); } return(response); }); } }
public async Task <string> LoginAsync(string link, string username, string password) { var loginLink = $"{link}/HomeAccess/Account/LogOn"; try { _httpClient.DefaultRequestHeaders.Referrer = new Uri($"{link}/HomeAccess/Account/LogOn"); _httpClient.DefaultRequestHeaders.CacheControl = CacheControlHeaderValue.Parse("max-age=0"); _httpClient.DefaultRequestHeaders.ExpectContinue = false; _httpClient.DefaultRequestHeaders.Add("Origin", @$ "{link}/"); foreach (var(key, value) in HandlerProperties) { _httpClient.DefaultRequestHeaders.Add(key, value); } var body = @"Database=10&LogOnDetails.UserName="******"&LogOnDetails.Password="******"application/x-www-form-urlencoded"); // tries to post a request with the http client try { var response = await _httpClient.PostAsync(loginLink, data); response.EnsureSuccessStatusCode(); return(await response.Content.ReadAsStringAsync()); } catch (HttpRequestException e) { SentrySdk.CaptureException(e); return(null); } } catch { return(null); } }
public static async Task <string> GetDataWithBody(HttpClient httpClient, string link, ResponseType type, string body, string section = "Student") { try { httpClient.DefaultRequestHeaders.Referrer = new Uri($"{link}/HomeAccess/Content/{section}/{type.ToString()}.aspx"); httpClient.DefaultRequestHeaders.CacheControl = CacheControlHeaderValue.Parse("max-age=0"); httpClient.DefaultRequestHeaders.ExpectContinue = false; httpClient.DefaultRequestHeaders.Add("Origin", @$ "{link}/"); foreach (var(key, value) in Login.HandlerProperties) { httpClient.DefaultRequestHeaders.Add(key, value); } var data = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded"); // tries to post a request with the http client try { var response = await httpClient.PostAsync(link, data); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); return(responseBody); } catch (HttpRequestException e) { SentrySdk.CaptureException(e); return(null); } } catch { return(null); } }
protected async override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { return(await Task.Run(() => { var metadata = _metadataProvider.GetMetadata(request); if (request.Headers.Any(h => h.Key == "X-Proxy-Type" && h.Value.Contains("metadata"))) { return request.CreateResponse(System.Net.HttpStatusCode.OK, metadata); } var template = new JsProxyTemplate(metadata); var js = new StringContent(template.TransformText()); js.Headers.ContentType = new MediaTypeHeaderValue("application/javascript"); js.Headers.Expires = DateTime.Now.AddDays(30).ToUniversalTime(); var result = new HttpResponseMessage { Content = js };; result.Headers.CacheControl = CacheControlHeaderValue.Parse("public"); return result; })); }
private static HttpRequestMessage GetRequestWithHeaders(DateTimeOffset?lastModified = null) { var request = new HttpRequestMessage { Headers = { CacheControl = CacheControlHeaderValue.Parse("public, max-age=31536000, must-revalidate"), Accept = { MediaTypeWithQualityHeaderValue.Parse("application/json"), MediaTypeWithQualityHeaderValue.Parse("text/html;q=0.9") } }, Content = new StringContent("") { Headers = { LastModified = lastModified, ContentLength = 123 } } }; return(request); }
public static HttpServerCacheHeaders BuildHeadersInflexible( bool cacheControlIsNull, bool sharedCache, bool noStore, bool immutable, TimeSpan?maxAge, TimeSpan?sMaxAge, FSharpOption <string> pragma, EntityTagHeaderValue eTag, FSharpOption <DateTime> exipiresUtc, FSharpOption <DateTime> lasModifiedUtc, FSharpOption <string> vary) { CacheControlHeaderValue cacheControl = null; if (!cacheControlIsNull) { cacheControl = immutable ? CacheControlHeaderValue.Parse("immutable") : new CacheControlHeaderValue(); cacheControl.NoStore = noStore; cacheControl.MaxAge = maxAge; cacheControl.SharedMaxAge = sMaxAge; cacheControl.Private = !sharedCache; } return(new HttpServerCacheHeaders( cacheControl ?? FSharpOption <CacheControlHeaderValue> .None, pragma ?? FSharpOption <string> .None, eTag ?? FSharpOption <EntityTagHeaderValue> .None, exipiresUtc ?? FSharpOption <DateTime> .None, lasModifiedUtc ?? FSharpOption <DateTime> .None, vary ?? FSharpOption <string> .None)); }
/// <summary> /// Constructs a web request to create a new block blob or page blob, or to update the content /// of an existing block blob. /// </summary> /// <param name="uri">The absolute URI to the blob.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="properties">The properties to set for the blob.</param> /// <param name="blobType">The type of the blob.</param> /// <param name="pageBlobSize">For a page blob, the size of the blob. This parameter is ignored /// for block blobs.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <returns>A web request to use to perform the operation.</returns> public static HttpRequestMessage Put(Uri uri, int?timeout, BlobProperties properties, BlobType blobType, long pageBlobSize, AccessCondition accessCondition, HttpContent content, OperationContext operationContext) { if (blobType == BlobType.Unspecified) { throw new InvalidOperationException(SR.UndefinedBlobType); } HttpRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, null /* builder */, content, operationContext); if (properties.CacheControl != null) { request.Headers.CacheControl = CacheControlHeaderValue.Parse(properties.CacheControl); } if (content != null) { if (properties.ContentType != null) { content.Headers.ContentType = MediaTypeHeaderValue.Parse(properties.ContentType); } if (properties.ContentMD5 != null) { content.Headers.ContentMD5 = Convert.FromBase64String(properties.ContentMD5); } if (properties.ContentLanguage != null) { content.Headers.ContentLanguage.Add(properties.ContentLanguage); } if (properties.ContentEncoding != null) { content.Headers.ContentEncoding.Add(properties.ContentEncoding); } if (properties.ContentDisposition != null) { content.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse(properties.ContentDisposition); } } if (blobType == BlobType.PageBlob) { request.Headers.Add(Constants.HeaderConstants.BlobType, Constants.HeaderConstants.PageBlob); request.Headers.Add(Constants.HeaderConstants.BlobContentLengthHeader, pageBlobSize.ToString(NumberFormatInfo.InvariantInfo)); properties.Length = pageBlobSize; } else if (blobType == BlobType.BlockBlob) { request.Headers.Add(Constants.HeaderConstants.BlobType, Constants.HeaderConstants.BlockBlob); } else { request.Headers.Add(Constants.HeaderConstants.BlobType, Constants.HeaderConstants.AppendBlob); } request.ApplyAccessCondition(accessCondition); return(request); }
public HttpResponseMessage Index() { HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.MovedPermanently); response.Headers.Location = new Uri("client/index.html", UriKind.Relative); response.Headers.CacheControl = CacheControlHeaderValue.Parse("no-cache, no-store, must-revalidate"); return(response); }
public void Parse_Invalid() { try { CacheControlHeaderValue.Parse("audio/"); Assert.Fail("#1"); } catch (FormatException) { } }
/// <inheritdoc /> public override void CacheControl(string value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } HttpClient.DefaultRequestHeaders.CacheControl = CacheControlHeaderValue.Parse(value); }
public void Parse() { var res = CacheControlHeaderValue.Parse("audio"); Assert.AreEqual("audio", res.Extensions.First().Name, "#1"); Assert.IsNull(res.Extensions.First().Value, "#2"); res = CacheControlHeaderValue.Parse(null); Assert.IsNull(res, "#3"); }
private static HttpClient CreateClient(Uri uri, string auth64) { var client = new HttpClient { BaseAddress = uri }; client.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse($"Basic {auth64}"); client.DefaultRequestHeaders.CacheControl = CacheControlHeaderValue.Parse("no-cache"); return(client); }
private HttpClient GetHttpClientAsync() { var httpClient = new HttpClient { BaseAddress = _baseUri }; httpClient.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse($"Basic {_auth64}"); httpClient.DefaultRequestHeaders.CacheControl = CacheControlHeaderValue.Parse("no-cache"); return(httpClient); }
public override void CacheControl(string value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } RequestMessage .Headers .CacheControl = CacheControlHeaderValue.Parse(value); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { HttpResponseMessage response = await base.SendAsync(request, cancellationToken); if (response.Headers.CacheControl == null) { response.Headers.CacheControl = CacheControlHeaderValue.Parse("no-cache, no-store"); response.Headers.Pragma.ParseAdd("no-cache"); } return(response); }
public HttpClient Client(TimeSpan?timeout = null) { return(new HttpClient { Timeout = timeout ?? TimeSpan.FromSeconds(100), DefaultRequestHeaders = { CacheControl = CacheControlHeaderValue.Parse("no-cache, no-store, must-revalidate"), Pragma = { NameValueHeaderValue.Parse("no-cache") } } }); }
private async Task <HttpResponseMessage> GetDataAsync(string segments) { string[] pathSegments = segments.Split(new[] { "/" }, StringSplitOptions.None); string alias = pathSegments[0]; string containerName = pathSegments[1]; string path = string.Join("/", pathSegments.Skip(2)); var storage = this.G2OConfiguration.Storage.FirstOrDefault(_ => _.Alias == alias); if (storage == null) { return(new HttpResponseMessage(HttpStatusCode.NotFound)); } if (!storage.Containers.Any(_ => _ == containerName)) { return(new HttpResponseMessage(HttpStatusCode.NotFound)); } var blobClient = storage.CloudStorageAccount.CreateCloudBlobClient(); var container = blobClient.GetContainerReference(containerName); var blob = container.GetBlockBlobReference(path); if (!await blob.ExistsAsync()) { return(new HttpResponseMessage(HttpStatusCode.NotFound)); } Stream blobStream = await blob.OpenReadAsync(); var message = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(blobStream) }; message.Content.Headers.ContentLength = blob.Properties.Length; if (!string.IsNullOrEmpty(blob.Properties.ContentType)) { message.Content.Headers.ContentType = new MediaTypeHeaderValue(blob.Properties.ContentType); } if (!string.IsNullOrEmpty(blob.Properties.ContentEncoding)) { message.Content.Headers.ContentEncoding.Add(blob.Properties.ContentEncoding); } if (!string.IsNullOrEmpty(blob.Properties.CacheControl)) { message.Headers.CacheControl = CacheControlHeaderValue.Parse(blob.Properties.CacheControl); } return(message); }
private void AddToCache(string resource, HttpResponseMessage response) { var cacheHeader = response.Headers.FirstOrDefault(h => h.Key == "cache-control"); if (string.IsNullOrEmpty(cacheHeader.Key)) { return; } var maxAge = CacheControlHeaderValue.Parse(cacheHeader.Value.ToString()).MaxAge; if (maxAge.HasValue) { m_Cache.Add(resource, response, maxAge.Value); } }
public async Task <dynamic> Get([FromRoute] string id) { Request.Headers.TryGetValue("If-None-Match", out StringValues clientEtag); string clientEtagStr = clientEtag.Count > 0 ? clientEtag.ToString() : null; try { var gridFsBucket = new GridFSBucket <ObjectId>(MongoWrapper.Database); var downloadStream = await gridFsBucket.OpenDownloadStreamAsync ( new ObjectId(id), new GridFSDownloadOptions { Seekable = true, CheckMD5 = false } ); if (clientEtagStr != null) { if (downloadStream.FileInfo.MD5.Equals(clientEtagStr.Trim('"'), StringComparison.Ordinal)) { Response.StatusCode = (int)HttpStatusCode.NotModified; return(new EmptyResult()); } } var fileMetadata = BsonSerializer.Deserialize <FileMetadata>(downloadStream.FileInfo.Metadata); string contentType = string.IsNullOrWhiteSpace(fileMetadata.ContentType) ? "application/octet-stream" : fileMetadata.ContentType; Response.GetTypedHeaders().CacheControl = CacheControlHeaderValue.Parse(CacheControlHeaderValue.NoCacheString); return(new FileStreamResult(downloadStream, contentType) { EnableRangeProcessing = true, EntityTag = new EntityTagHeaderValue("\"" + downloadStream.FileInfo.MD5 + "\"") }); } catch (GridFSFileNotFoundException) { return(new ResponseBody { Code = ResponseCode.NotFound, Message = "Arquivo não foi encontrado!", Success = false }); } }
/// <summary> /// Constructs a web request to create a new file. /// </summary> /// <param name="uri">The absolute URI to the file.</param> /// <param name="timeout">The server timeout interval.</param> /// <param name="properties">The properties to set for the file.</param> /// <param name="fileSize">For a file, the size of the file. This parameter is ignored /// for block files.</param> /// <param name="accessCondition">The access condition to apply to the request.</param> /// <returns>A web request to use to perform the operation.</returns> public static StorageRequestMessage Create(Uri uri, int?timeout, FileProperties properties, long fileSize, AccessCondition accessCondition, HttpContent content, OperationContext operationContext, ICanonicalizer canonicalizer, StorageCredentials credentials) { CommonUtility.AssertNotNull("properties", properties); StorageRequestMessage request = HttpRequestMessageFactory.CreateRequestMessage(HttpMethod.Put, uri, timeout, null /* builder */, content, operationContext, canonicalizer, credentials); if (properties.CacheControl != null) { request.Headers.CacheControl = CacheControlHeaderValue.Parse(properties.CacheControl); } if (content != null) { if (properties.ContentType != null) { content.Headers.ContentType = MediaTypeHeaderValue.Parse(properties.ContentType); } if (properties.ContentMD5 != null) { content.Headers.ContentMD5 = Convert.FromBase64String(properties.ContentMD5); } if (properties.ContentLanguage != null) { content.Headers.ContentLanguage.Add(properties.ContentLanguage); } if (properties.ContentEncoding != null) { content.Headers.ContentEncoding.Add(properties.ContentEncoding); } if (properties.ContentDisposition != null) { content.Headers.ContentDisposition = ContentDispositionHeaderValue.Parse(properties.ContentDisposition); } } request.Headers.Add(Constants.HeaderConstants.FileType, Constants.HeaderConstants.File); request.Headers.Add(Constants.HeaderConstants.FileContentLengthHeader, fileSize.ToString(NumberFormatInfo.InvariantInfo)); properties.Length = fileSize; request.ApplyAccessCondition(accessCondition); return(request); }
public static async Task <Stream> PostStreamAsync(Uri url, HttpContent content) { using HttpClient client = new(); client.DefaultRequestHeaders.Add("User-Agent", UAGENT); client.DefaultRequestHeaders.CacheControl = CacheControlHeaderValue.Parse("no-cache"); using HttpResponseMessage resp = await client.PostAsync(url, content); if (resp.IsSuccessStatusCode) { return(await resp.Content.ReadAsStreamAsync()); } else { return(null); } }
public void Parse() { var res = CacheControlHeaderValue.Parse("audio"); Assert.AreEqual("audio", res.Extensions.First().Name, "#1"); Assert.IsNull(res.Extensions.First().Value, "#2"); Assert.AreEqual("audio", res.ToString(), "#3"); res = CacheControlHeaderValue.Parse(null); Assert.IsNull(res, "#4"); res = CacheControlHeaderValue.Parse("no-cache, no-store , max-age = 44, max-stale = 66, min-fresh=333 ,no-transform, only-if-cached"); Assert.IsTrue(res.NoCache, "#10"); Assert.IsTrue(res.NoStore, "#11"); Assert.AreEqual(new TimeSpan(0, 0, 44), res.MaxAge, "#12"); Assert.IsTrue(res.MaxStale, "#13"); Assert.AreEqual(new TimeSpan(0, 1, 6), res.MaxStaleLimit, "#14"); Assert.AreEqual(new TimeSpan(0, 5, 33), res.MinFresh, "#15"); Assert.IsTrue(res.NoTransform, "#16"); Assert.IsTrue(res.OnlyIfCached, "#17"); Assert.AreEqual("no-store, no-transform, only-if-cached, no-cache, max-age=44, max-stale=66, min-fresh=333", res.ToString(), "#18"); res = CacheControlHeaderValue.Parse("anu = 333"); Assert.AreEqual("anu", res.Extensions.First().Name, "#20"); Assert.AreEqual("333", res.Extensions.First().Value, "#21"); Assert.AreEqual("anu=333", res.ToString(), "#22"); res = CacheControlHeaderValue.Parse("public, private = \"nnn \", no-cache =\"mmm\" , must-revalidate, proxy-revalidate, s-maxage=443"); Assert.IsTrue(res.Public, "#30"); Assert.IsTrue(res.Private, "#31"); Assert.AreEqual("nnn", res.PrivateHeaders.First(), "#32"); Assert.IsTrue(res.NoCache, "#33"); Assert.AreEqual("mmm", res.NoCacheHeaders.First(), "#34"); Assert.IsTrue(res.MustRevalidate, "#35"); Assert.IsTrue(res.ProxyRevalidate, "#36"); Assert.AreEqual(new TimeSpan(0, 7, 23), res.SharedMaxAge, "#37"); Assert.AreEqual("public, must-revalidate, proxy-revalidate, no-cache=\"mmm\", s-maxage=443, private=\"nnn\"", res.ToString(), "#38"); res = CacheControlHeaderValue.Parse("private = \"nnn , oo, xx\", bb= \" x \""); Assert.IsTrue(res.Private, "#40"); Assert.AreEqual(3, res.PrivateHeaders.Count, "#41"); Assert.AreEqual("oo", res.PrivateHeaders.ToList()[1], "#42"); Assert.AreEqual("\" x \"", res.Extensions.First().Value, "#43"); Assert.AreEqual("private=\"nnn, oo, xx\", bb=\" x \"", res.ToString(), "#44"); }
HttpRequestMessage BuildRequest(UriBuilder uri) { var request = new HttpRequestMessage(Method, new Uri(uri.ToString())); request.Headers.CacheControl = CacheControlHeaderValue.Parse("no-cache, no-store, must-revalidate"); if (Properties.Count > 0) { foreach (var prop in Properties) { request.Headers.Add(prop.Key, prop.Value); } } Content?.WriteContent(request); return(request); }
public HttpClient Client(TimeSpan?timeout = null) { var configuration = NSUrlSessionConfiguration.DefaultSessionConfiguration; configuration.TimeoutIntervalForRequest = timeout?.Seconds ?? 100; var handler = new NSUrlSessionHandler(configuration) { DisableCaching = true }; return(new HttpClient(handler) { DefaultRequestHeaders = { CacheControl = CacheControlHeaderValue.Parse("no-cache, no-store, must-revalidate"), Pragma = { NameValueHeaderValue.Parse("no-cache") } } }); }
public CacheControl(HttpCachedClient parent, HttpResponseMessage response) { var headers = response.Headers; var contentHeaders = response.Content.Headers; Date = headers.Date ?? DateTimeOffset.UtcNow; Value = headers.CacheControl ?? CacheControlHeaderValue.Parse(headers.Pragma.ToString()); ShouldCache = Value.Public || (Value.Private && parent.Shared) || !Value.NoStore; // 4.2.1. Calculating Freshness Lifetime FreshnessLifetime = parent.Shared && Value.SharedMaxAge != null && Value.SharedMaxAge.Value.TotalSeconds != 0 ? Value.SharedMaxAge : Value.MaxAge != null && Value.MaxAge.Value.TotalSeconds != 0 ? Value.MaxAge : contentHeaders.Expires != null ? (TimeSpan?)contentHeaders.Expires.Value.Subtract(Date) : contentHeaders.LastModified != null ? (TimeSpan?)TimeSpan.FromSeconds(contentHeaders.LastModified.Value.Subtract(Date).TotalSeconds / 10) : null; Validation = !Value.NoCache && (Value.MaxAge == null || Value.MaxAge.Value.TotalSeconds != 0) ? (Func <Func <Task <HttpResponseMessage> >, HttpRequestMessage, Task <HttpResponseMessage> >)null : headers.ETag != null ? (b, r) => IfNoneMatch(b, r, headers.ETag) : contentHeaders.LastModified != null ? (b, r) => IfModifiedSince(b, r, contentHeaders.LastModified.Value) : (Func <Func <Task <HttpResponseMessage> >, HttpRequestMessage, Task <HttpResponseMessage> >)null; }
private void AddToCache(string resource, HttpResponseMessage response) { // Reads the cache-control header from the response var cacheHeader = response.Headers.FirstOrDefault(h => h.Key.Equals("cache-control", StringComparison.OrdinalIgnoreCase)); if (string.IsNullOrEmpty(cacheHeader.Key)) { return; } // Parses the cache-control value and extracts maxage from it var maxAge = CacheControlHeaderValue.Parse(cacheHeader.Value.FirstOrDefault()).MaxAge; if (maxAge.HasValue) { // Adds the response to the cache if it has a max-age value _cache.Add(key: resource, value: response, ttl: maxAge.Value); } }
private void AddToCache(string resource, HttpResponseMessage response) { var cacheHeader = response .Headers .FirstOrDefault(h => h.Key.ToLower() == "cache-control"); if (string.IsNullOrEmpty(cacheHeader.Key)) { return; } var maxAge = CacheControlHeaderValue.Parse(cacheHeader.Value.FirstOrDefault()) .MaxAge; if (maxAge.HasValue) { this._cache.Add(key: resource, value: response, ttl: maxAge.Value); } }
public CDOSession(CDOSessionOptions options) { Options = options; Instance = this; //used by cdo when no session object is passed //init httpclient HttpClient = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip }); //HttpClient = new HttpClient(new HttpClientHandler() { SslProtocols = _options.SslProtocols }); //this is not supported in older frameworks & problematic in Outlook VSTO ServicePointManager.SecurityProtocol = Options.SecurityProtocol; HttpClient.DefaultRequestHeaders.ConnectionClose = false; HttpClient.DefaultRequestHeaders.CacheControl = CacheControlHeaderValue.Parse("no-cache"); HttpClient.DefaultRequestHeaders.Pragma.Add(NameValueHeaderValue.Parse("no-cache")); HttpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); Task.Factory.StartNew(() => NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged).Wait(); }
public void ConfigureHttpClient(NexusNodeEndpoint endpoint) { if (_client == null) { throw new NullReferenceException("Http client is null"); } if (endpoint == null) { throw new ArgumentException("Parameters are missing"); } if (string.IsNullOrWhiteSpace(endpoint.Url)) { throw new ArgumentException("URL is missing"); } if (string.IsNullOrWhiteSpace(endpoint.Username)) { throw new ArgumentException("Username is missing"); } if (string.IsNullOrWhiteSpace(endpoint.Password)) { throw new ArgumentException("Password is missing"); } var uriResult = Uri.TryCreate(endpoint.Url, UriKind.Absolute, out var baseUri) && (baseUri.Scheme == Uri.UriSchemeHttp || baseUri.Scheme == Uri.UriSchemeHttps); if (!uriResult) { throw new Exception("Url is not valid"); } var auth64 = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{endpoint.Username}:{endpoint.Password}")); _client.BaseAddress = baseUri; _client.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue.Parse($"Basic {auth64}"); _client.DefaultRequestHeaders.CacheControl = CacheControlHeaderValue.Parse("no-cache"); }