public void SetProperties(HttpResponseHeaders headers) { var properties = this.GetType().GetTypeInfo().DeclaredProperties; foreach (var prop in properties.Where(prop => headers.Any(h => h.Key == prop.Name))) { var value = headers.First(h => NetNamingMapper.GetPropertyName(h.Key) == prop.Name).Value; if(value == null) continue; if (value.Count() == 1) { prop.SetValue(this, value.FirstOrDefault()); } else { try { prop.SetValue(this, value.FirstOrDefault()); } catch (Exception) { // do nothing } } } }
private Dictionary<string, string> ConvertHeaders(HttpResponseHeaders responseHeaders, HttpContent httpContent) { if ((responseHeaders == null || !responseHeaders.Any()) && (httpContent == null || (httpContent.Headers == null || !httpContent.Headers.Any()))) { return null; } var headers = new Dictionary<string, string>(); if (responseHeaders != null && responseHeaders.Any()) { foreach (var responseHeader in responseHeaders) { headers.Add(responseHeader.Key, String.Join(", ", responseHeader.Value.Select(x => x))); } } if (httpContent != null && httpContent.Headers != null && httpContent.Headers.Any()) { foreach (var contentHeader in httpContent.Headers) { headers.Add(contentHeader.Key, String.Join(", ", contentHeader.Value.Select(x => x))); } } return headers; }
/// <summary> /// End request /// </summary> /// <param name="correlationId">Id which persists throughout the request</param> /// <param name="requestMethod">Current method (GET, POST, etc)</param> /// <param name="requestUri">Current uri requested</param> /// <param name="message">Response message</param> /// <param name="responseHeaders">Response headers</param> /// <param name="processingTime">Total internal processing time in milliseconds</param> /// <returns></returns> protected void OutgoingRequest(string correlationId, string requestMethod, string requestUri, byte[] message, HttpResponseHeaders responseHeaders, long processingTime) { responseHeaders.Add("X-Correlation-Id", correlationId); responseHeaders.Add("X-Processing-Time", processingTime.ToString(CultureInfo.InvariantCulture)); Log.Information("Total internal processing time: {processingTime:000} ms", processingTime); }
public HttpHeadersAbstraction(HttpResponseHeaders headers) { foreach (var header in headers) { this._headers.Add(header.Key,header.Value); } }
internal static void CopyTo(this HttpResponseHeaders from, HttpResponseHeaders to) { foreach (var header in from) { to.TryAddWithoutValidation(header.Key, header.Value); } }
private void AddIfMissing(HttpResponseHeaders headers, string header, string value) { if (!headers.Contains(header)) { headers.Add(header, value); } }
public HttpResponse(HttpResponseMessage responseMessage) { ContentEncoding = responseMessage.Content.Headers.ContentEncoding.FirstOrDefault(); ContentLength = responseMessage.Content.Headers.ContentLength.Value; if(responseMessage.Content.Headers.ContentType != null) { CharacterSet = responseMessage.Content.Headers.ContentType.CharSet; ContentType = responseMessage.Content.Headers.ContentType.MediaType; } //Cookies = httpWebResponse.Cookies; Headers = responseMessage.Headers; //IsFromCache = httpWebResponse.IsFromCache; //IsMutuallyAuthenticated = httpWebResponse.IsMutuallyAuthenticated; //LastModified = httpWebResponse.LastModified; Method = responseMessage.RequestMessage.Method.ToString(); //ProtocolVersion = httpWebResponse.ProtocolVersion; //ResponseUri = httpWebResponse.ResponseUri; //Server = httpWebResponse.Server; HttpStatusCode = (int)responseMessage.StatusCode; StatusDescription = responseMessage.ReasonPhrase; }
public void AddRange(HttpResponseHeaders headers) { foreach (var header in headers) { this._headers.Add(header.Key, header.Value); } }
public void SetProperties(HttpResponseHeaders headers) { var properties = this.GetType().GetProperties().Where(p => p.GetValue(this) != null); foreach (var prop in properties.Where(prop => headers.Any(h => h.Key == prop.Name))) { prop.SetValue(this, headers.First(h => NetNamingMapper.GetPropertyName(h.Key) == prop.Name)); } }
public ActionResponseEntry(HttpResponseMessage result) { _statusCode = result.StatusCode; _content = result.Content == null ? "[NULL]" : result.Content.ReadAsStringAsync().Result; _headers = result.Headers; }
public HttpResponseHeadersAdapter (HttpResponseHeaders headersFromFirstCall, HttpResponseHeaders headersFromLastCall) { if (headersFromFirstCall == null) throw new ArgumentNullException ("headersFromFirstCall"); if (headersFromLastCall == null) throw new ArgumentNullException ("headersFromLastCall"); _headersFromFirstCall = headersFromFirstCall; _headersFromLastCall = headersFromLastCall; }
public static void CopyTo(this HttpResponseHeaders fromHeaders, HttpResponseHeaders toHeaders) { Contract.Assert(fromHeaders != null, "fromHeaders cannot be null."); Contract.Assert(toHeaders != null, "toHeaders cannot be null."); foreach (KeyValuePair<string, IEnumerable<string>> header in fromHeaders) { toHeaders.TryAddWithoutValidation(header.Key, header.Value); } }
/// <summary> /// Identifies SEO meta tag values in the specified response headers and attempts to injects them into /// the specified page via content placeholders assumed to exist in the page's master page. /// </summary> /// <param name="page">A reference to the current page.</param> /// <param name="headers">Response headers from an HTTP request.</param> public static void InjectSeoMetaTagsIntoPage(HttpResponseHeaders headers) { if (HttpContext.Current == null) return; var page = HttpContext.Current.Handler as Page; if (page == null || headers == null) return; // Look for new values within HTTP headers IEnumerable<string> seoData = null; if (headers.TryGetValues(Constants.SeoFields.SeoData, out seoData)) { // Deserialize new values var serializer = new DataContractJsonSerializer(typeof(Dictionary<string, string>)); var seoValues = (Dictionary<string, string>)serializer.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(seoData.First()))); // Get master page placeholder controls var pageTitleControl = page.Master.FindControl(Constants.ContentPlaceholders.PageTitle); var seoMetaTagControl = page.Master.FindControl(Constants.ContentPlaceholders.SeoMetaTags); var canonicalUrlControl = page.Master.FindControl(Constants.ContentPlaceholders.CanonicalUrlMetaTag); var seoH1Control = page.Master.FindControl(Constants.ContentPlaceholders.SeoH1Tag); // Inject values into controls if (pageTitleControl != null && seoValues.ContainsKey(Constants.SeoFields.PageTitle)) { pageTitleControl.Controls.Clear(); pageTitleControl.Controls.Add(new LiteralControl("<title>" + seoValues[Constants.SeoFields.PageTitle] + "</title>")); } if (canonicalUrlControl != null && seoValues.ContainsKey(Constants.SeoFields.CanonicalUrl)) { canonicalUrlControl.Controls.Clear(); canonicalUrlControl.Controls.Add(new LiteralControl("<link rel=\"canonical\" href=\"" + seoValues[Constants.SeoFields.CanonicalUrl] + "\"/>")); } if (seoH1Control != null && seoValues.ContainsKey(Constants.SeoFields.H1)) { seoH1Control.Controls.Clear(); seoH1Control.Controls.Add(new LiteralControl("<h1 class=\"ih-seo-title\" itemprop=\"name\">" + seoValues[Constants.SeoFields.H1] + "</h1>")); } if (seoMetaTagControl != null) { var newMetaTags = CreateSeoMetaTagsFromValues(seoValues); var oldMetaTags = ((LiteralControl)seoMetaTagControl.Controls[0]).Text; var finalMetaTags = MergeSeoMetaTags(newMetaTags, oldMetaTags); seoMetaTagControl.Controls.Clear(); seoMetaTagControl.Controls.Add(new LiteralControl(finalMetaTags)); } } }
public static PaginationInfo FindAndParsePaginationInfo(HttpResponseHeaders responseHeaders) { //find x-pagination if (responseHeaders.Contains("X-Pagination")) { var xPag = responseHeaders.First(rh => rh.Key == "X-Pagination").Value; return JsonConvert.DeserializeObject<PaginationInfo>(xPag.First()); } return null; }
public static PagingInfo FindAndParsePagingInfo(HttpResponseHeaders responseHeaders) { // find the "X-Pagination" info in header if (responseHeaders.Contains("X-Pagination")) { var xPag = responseHeaders.First(ph => ph.Key == "X-Pagination").Value; // parse the value - this is a JSON-string. return JsonConvert.DeserializeObject<PagingInfo>(xPag.First()); } return null; }
internal ApiException( HttpStatusCode statusCode, string reasonPhrase, HttpResponseHeaders headers, HttpContentHeaders contentHeaders, string content) : base(String.Format("Response status code does not indicate success: {0} ({1}).", (int)statusCode, reasonPhrase)) { this.StatusCode = statusCode; this.ReasonPhrase = reasonPhrase; this.Headers = headers; this.ContentHeaders = contentHeaders; this.Content = content; }
private static long GetHeaderValue(HttpResponseHeaders headers, string name) { long result = 0; IEnumerable<string> values = null; headers.TryGetValues(name, out values); string value = values?.FirstOrDefault(); if (value != null) { long.TryParse(value, out result); } return result; }
private static RateLimit ParseRateLimit(HttpResponseHeaders headers) { // Determine reset long resetInUnixTime = GetHeaderValue(headers, "x-ratelimit-reset"); DateTimeOffset epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero); DateTimeOffset reset = epoch.AddSeconds(resetInUnixTime); return new RateLimit { Limit = GetHeaderValue(headers, "x-ratelimit-limit"), Remaining = GetHeaderValue(headers, "x-ratelimit-remaining"), Reset = reset }; }
public PocoHttpResponseException(HttpResponseMessage response) :this(string.Format("Status {0}", response.StatusCode)) { _responseHeaders = response.Headers; _statusCode = response.StatusCode; try { if (response.Content != null) _content = response.Content.ReadAsByteArrayAsync().Result; } catch { // swallow } }
public async Task<GistObject> CreateAGist(string description, bool isPublic, IEnumerable<Tuple<string, string>> fileContentCollection) { using (HttpClient httpClient = this.CreateHttpClient()) { var requestUri = new Uri(string.Format("https://api.github.com/gists?access_token={0}", this._accessToken)); string content = MakeCreateContent(description, isPublic, fileContentCollection); var data = new StringContent(content, Encoding.UTF8, "application/json"); var response = await httpClient.PostAsync(requestUri, data, this.cancellationTS.Token); this._responseHeaders = response.Headers; string json = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync(); return (GistObject)DynamicToGistObject((dynamic)DynamicJson.Parse(json)); } }
protected void SendRequest(HttpRequestMessage request, bool contentInBytes = false) { using (var response = Client.SendAsync(request).Result) { StatusCode = response.StatusCode; Headers = response.Headers; if (contentInBytes) { ContentBytes = response.Content == null ? null : response.Content.ReadAsByteArrayAsync().Result; } else { Content = response.Content == null ? null : response.Content.ReadAsStringAsync().Result; } } }
public Pages(HttpResponseHeaders headers) { if (headers.Contains("Link")) { var links = headers.ParseLinkHeaders(new Uri("https://api.github.com/"), new LinkRegistry()); var nextLink = links.SingleOrDefault(link => link.Relation == "next"); var firstLink = links.SingleOrDefault(link => link.Relation == "first"); var lastLink = links.SingleOrDefault(link => link.Relation == "last"); var previousLink = links.SingleOrDefault(link => link.Relation == "prev"); if (nextLink != null) Next = Convert.ToInt32(nextLink.Target.ParseQueryString()["page"]); if (firstLink != null) First = Convert.ToInt32(firstLink.Target.ParseQueryString()["page"]); if (lastLink != null) Last = Convert.ToInt32(lastLink.Target.ParseQueryString()["page"]); if (previousLink != null) Previous = Convert.ToInt32(previousLink.Target.ParseQueryString()["page"]); } }
internal HttpResponseMessage(WebResponse response, HttpRequestMessage request) { var stream = response.GetResponseStream(); if (stream != null) Content = new StreamContent(stream) { Headers = new HttpContentHeaders(response.Headers) }; if (response.SupportsHeaders) { Headers = new HttpResponseHeaders(response.Headers); } if (response is HttpWebResponse) { var httpResponse = response as HttpWebResponse; StatusCode = httpResponse.StatusCode; IsSuccessStatusCode = ((int)StatusCode >= 200 && (int)StatusCode <= 299); ReasonPhrase = httpResponse.StatusDescription; } RequestMessage = request; }
private void ExtractHeaderLinks(HttpResponseHeaders responseHeaders, SemanticsRegistry linkFactory) { _HeaderLinks = new List<Link>(); foreach (var header in responseHeaders.Where(h => h.Key.ToLowerInvariant() == "link")) { var links = header.Value.First(); foreach (Match match in LinkHeaderParser.Matches(links)) { string relation = null; if (match.Groups["rel"].Success) { relation = match.Groups["rel"].Value; } var link = linkFactory.CreateLink(relation); link.Target = new Uri(match.Groups["href"].Value, UriKind.RelativeOrAbsolute); _HeaderLinks.Add(link); } } }
public void TryParseAdd_AddBadAfterGoodValue_False() { HttpResponseHeaders headers = new HttpResponseHeaders(); headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Negotiate")); string input = "Basic, D\rigest qop=\"auth\",algorithm=MD5-sess"; Assert.False(headers.WwwAuthenticate.TryParseAdd(input)); Assert.Equal("Negotiate", headers.WwwAuthenticate.ToString()); Assert.Equal("WWW-Authenticate: Negotiate\r\n", headers.ToString()); }
public void TryParseAdd_AddBadValue_False() { HttpResponseHeaders headers = new HttpResponseHeaders(); string input = "Basic, D\rigest qop=\"auth\",algorithm=MD5-sess"; Assert.False(headers.WwwAuthenticate.TryParseAdd(input)); Assert.Equal(string.Empty, headers.WwwAuthenticate.ToString()); Assert.Equal(string.Empty, headers.ToString()); }
public void TryParseAdd_CallWithNullValue_NothingAdded() { HttpResponseHeaders headers = new HttpResponseHeaders(); Assert.True(headers.WwwAuthenticate.TryParseAdd(null)); Assert.False(headers.WwwAuthenticate.IsSpecialValueSet); Assert.Equal(0, headers.WwwAuthenticate.Count); Assert.Equal(String.Empty, headers.WwwAuthenticate.ToString()); }
public void ParseAdd_AddBadValue_Throws() { HttpResponseHeaders headers = new HttpResponseHeaders(); string input = "Basic, D\rigest qop=\"auth\",algorithm=MD5-sess"; Assert.Throws<FormatException>(() => { headers.WwwAuthenticate.ParseAdd(input); }); }
internal void CacheResponse(string url, RavenJToken data, HttpResponseHeaders headers) { if (headers.ETag == null || string.IsNullOrEmpty(headers.ETag.Tag)) return; var clone = data.CloneToken(); clone.EnsureCannotBeChangeAndEnableSnapshotting(); cache.Set(url, new CachedRequest { Data = clone, Time = SystemTime.UtcNow, Headers = new NameValueCollection(),// TODO: Use headers Database = MultiDatabase.GetDatabaseName(url) }); }
internal RavenJToken GetCachedResponse(HttpJsonRequest httpJsonRequest, HttpResponseHeaders additionalHeaders) { if (httpJsonRequest.CachedRequestDetails == null) throw new InvalidOperationException("Cannot get cached response from a request that has no cached information"); httpJsonRequest.ResponseStatusCode = HttpStatusCode.NotModified; httpJsonRequest.ResponseHeaders = new NameValueCollection(httpJsonRequest.CachedRequestDetails.Headers); if (additionalHeaders != null) { string forcePrimaryServerCHeck = additionalHeaders.GetFirstValue(Constants.RavenForcePrimaryServerCheck); if (forcePrimaryServerCHeck != null) httpJsonRequest.ResponseHeaders.Add(Constants.RavenForcePrimaryServerCheck, forcePrimaryServerCHeck); } IncrementCachedRequests(); return httpJsonRequest.CachedRequestDetails.Data.CloneToken(); }
public ResponseObject(HttpStatusCode statusCode, HttpResponseHeaders responseHeader, string responseBody) { this.statusCode = statusCode; this.responseHeader = responseHeader; this.responseBody = responseBody; }