public static void SetNoCache(this HttpResponseHeaders responseHeaders) { if (!responseHeaders.Contains("Cache-Control")) { responseHeaders.Add("Cache-Control", "no-store, no-cache, max-age=0"); } if (!responseHeaders.Contains("Pragma")) { responseHeaders.Add("Pragma", "no-cache"); } }
public void Headers_GetEnumerator() { HttpResponseMessage message = new HttpResponseMessage(); HttpResponseHeaders headers = message.Headers; headers.Add("a", new[] { "v1", "v2" }); headers.Add("cache-control", "audio"); headers.Age = new TimeSpan(4444, 2, 3, 4, 5); int i = 0; List <string> values; foreach (var entry in headers) { switch (i) { case 0: Assert.AreEqual("a", entry.Key); values = entry.Value.ToList(); Assert.AreEqual(2, values.Count); Assert.AreEqual("v1", values[0]); break; case 1: #if !__WATCHOS__ if (HttpClientTestHelpers.UsingSocketsHandler) #endif Assert.AreEqual("Cache-Control", entry.Key); #if !__WATCHOS__ else { Assert.AreEqual("cache-control", entry.Key); } #endif values = entry.Value.ToList(); Assert.AreEqual(1, values.Count); Assert.AreEqual("audio", values[0]); break; case 2: Assert.AreEqual("Age", entry.Key); values = entry.Value.ToList(); Assert.AreEqual(1, values.Count); Assert.AreEqual("383968984", values[0]); break; } ++i; } Assert.AreEqual(3, i, "#10"); }
internal IHttpResponse BuildHttpResponse(HttpWebResponse httpWebResponse) { var responseHeaders = new HttpResponseHeaders(); foreach (var headerName in httpWebResponse.Headers.AllKeys) { var headerValues = httpWebResponse.Headers.GetValues(headerName); if (headerValues != null) { foreach (var headerValue in headerValues) { responseHeaders.Add(headerName, headerValue); } } } var responseBodyStream = new MemoryStream(); using (var responseStream = httpWebResponse.GetResponseStream()) { responseStream?.CopyTo(responseBodyStream); } return(new HttpResponse { StatusCode = httpWebResponse.StatusCode, StatusText = httpWebResponse.StatusDescription, Headers = responseHeaders, Url = httpWebResponse.ResponseUri, Body = responseBodyStream }); }
private static void CopyHeaders(Windows.Web.Http.Headers.HttpResponseHeaderCollection input, HttpResponseHeaders output) { foreach (var header in input) { output.Add(header.Key, header.Value); } }
public async Task CreateAsync_should_create_and_return_new_todo() { var todo = new Todo(0, 456, "go shopping"); var expected = new Todo(2, 456, "go shopping"); var responseHeaders = new HttpResponseHeaders(); responseHeaders.Add("Location", $"https://localhost/todos/{expected.Id}"); // pass lambda predicate to validate request content // response from the HTTP Post method will have 201 status code and Location header mock.SetupPost <Todo>("/todos", content: x => x.UserId == todo.UserId && x.Title == todo.Title && x.Completed == todo.Completed).ReturnsAsync(201, responseHeaders); mock.SetupGet($"/todos/{expected.Id}").ReturnsAsync(expected); var actual = await service.CreateAsync(todo); Assert.Equal(expected.Id, actual.Id); Assert.Equal(expected.UserId, actual.UserId); Assert.Equal(expected.Title, actual.Title); Assert.Equal(expected.Completed, actual.Completed); }
/// <summary>Sets the Link HTTP header to the given urls.</summary> /// <param name="source">The source.</param> /// <param name="links">The list of URLs.</param> /// <remarks> /// Any existing Link header is replaced with the new values. /// <para /> /// Multiple links with the same relation are not filtered out. /// </remarks> public static void SetLink(this HttpResponseHeaders source, IEnumerable <HeaderLinkUrl> links) { //Remove any existing link header source.Remove(StandardHeaders.Links); //Links are source.Add(StandardHeaders.Links, String.Join(",", links)); }
public static void Set(this HttpResponseHeaders headers, string name, string value) { if (headers.Contains(name)) { headers.Remove(name); } headers.Add(name, value); }
// Private & internal methods internal static bool AddPublicationStateInfoHeader(this HttpResponseHeaders responseHeaders, PublicationStateInfo psi) { if (responseHeaders.Contains(FusionHeaders.Publication)) { return(false); } responseHeaders.Add(FusionHeaders.Publication, JsonConvert.SerializeObject(psi)); return(true); }
internal static void AddClientCacheStatusHeader(this HttpResponseHeaders headers, CacheStatus status) { if (headers == null) { throw new ArgumentNullException(nameof(headers)); } headers.Remove(CashewStatusHeader); headers.Add(CashewStatusHeader, GetHeaderStringValue(status)); }
protected override void CustomizeHttpResponseHeaders(HttpResponseHeaders responseHeaders) { // HTTP 1.1. responseHeaders.CacheControl.NoCache = true; responseHeaders.CacheControl.NoStore = true; responseHeaders.CacheControl.MustRevalidate = true; // HTTP 1.0. responseHeaders.Add("Pragma", "no-cache"); // HTTP 1.0. }
public void Headers_GetEnumerator() { HttpResponseMessage message = new HttpResponseMessage(); HttpResponseHeaders headers = message.Headers; headers.Add("a", new[] { "v1", "v2" }); headers.Add("cache-control", "audio"); headers.Age = new TimeSpan(4444, 2, 3, 4, 5); int i = 0; List <string> values; foreach (var entry in headers) { switch (i) { case 0: Assert.AreEqual("a", entry.Key); values = entry.Value.ToList(); Assert.AreEqual(2, values.Count); Assert.AreEqual("v1", values[0]); break; case 1: Assert.AreEqual("cache-control", entry.Key); values = entry.Value.ToList(); Assert.AreEqual(1, values.Count); Assert.AreEqual("audio", values[0]); break; case 2: Assert.AreEqual("Age", entry.Key); values = entry.Value.ToList(); Assert.AreEqual(1, values.Count); Assert.AreEqual("383968984", values[0]); break; } ++i; } Assert.AreEqual(3, i, "#10"); }
public static void CopyTo(this HttpResponseHeaders fromHeaders, HttpResponseHeaders toHeaders) { Fx.Assert(fromHeaders != null, "fromHeaders cannot be null."); Fx.Assert(toHeaders != null, "toHeaders cannot be null."); foreach (KeyValuePair <string, IEnumerable <string> > header in fromHeaders) { toHeaders.Add(header.Key, header.Value); } }
public void Header_BaseImplementation() { HttpResponseMessage message = new HttpResponseMessage(); HttpResponseHeaders headers = message.Headers; headers.Add("a", "a-value"); headers.Add("b", new List <string> { "v1", "v2" }); headers.Add("c", null as string); headers.Add("d", new string[0]); headers.TryAddWithoutValidation("cache-control", "audio"); Assert.IsFalse(headers.Contains("nn"), "#1a"); Assert.IsTrue(headers.Contains("b"), "#1b"); var values = headers.GetValues("b").ToList(); Assert.AreEqual("v1", values[0], "#2a"); Assert.AreEqual("v2", values[1], "#2b"); Assert.IsFalse(headers.Remove("p"), "#3a"); Assert.IsTrue(headers.Remove("b"), "#3b"); Assert.IsFalse(headers.Contains("b"), "#3b-c"); IEnumerable <string> values2; Assert.IsTrue(headers.TryGetValues("c", out values2)); values = values2.ToList(); Assert.AreEqual("", values[0], "#4a"); int counter = 0; foreach (var i in headers) { ++counter; } Assert.AreEqual(3, counter, "#5"); headers.Clear(); }
protected override void DoSetServiceHeaders(IStateContainer state, HttpResponseHeaders headers) { var sw = state.GetState <Stopwatch>(StardustTimerKey); if (sw == null) { return; } sw.Stop(); headers.Add(StardustTimerKey, sw.ElapsedMilliseconds.ToString()); }
public void Headers_Request() { HttpResponseMessage message = new HttpResponseMessage(); HttpResponseHeaders headers = message.Headers; headers.Add("accept", "audio"); Assert.AreEqual("audio", headers.GetValues("Accept").First(), "#1"); headers.Clear(); Assert.IsTrue(headers.TryAddWithoutValidation("accept", "audio"), "#2a"); Assert.AreEqual("audio", headers.GetValues("Accept").First(), "#2"); }
public void Trailer_AddAndGetAllowedContentHeader_Success(string name, string value) { var trailingHeaders = new HttpResponseHeaders(containsTrailingHeaders: true); trailingHeaders.Add(name, value); var actualHeaderValues = trailingHeaders.GetValues(name).ToArray(); Assert.Equal(1, actualHeaderValues.Length); Assert.Equal(value, actualHeaderValues[0]); }
public static void SetCache(this HttpResponseHeaders responseHeaders, int maxAge) { if (maxAge == 0) { responseHeaders.SetNoCache(); } else if (maxAge > 0) { if (!responseHeaders.Contains("Cache-Control")) { responseHeaders.Add("Cache-Control", $"max-age={maxAge}"); } } }
public void SetServiceHeaders(HttpResponseHeaders headers) { try { headers.Add("x-serviceVersion", ServiceVersion); headers.Add("x-uptime", (DateTime.UtcNow - StartTime).ToString("g")); headers.Add("x-region", Environment.GetEnvironmentVariable("REGION_NAME")); var user = _provider.GetService <IUserNameResolver>()?.GetCurrentUserName(); if (!string.IsNullOrWhiteSpace(user)) { headers.Add("x-principal", user); } var actor = _provider.GetService <IUserNameResolver>()?.GetActorId(); if (!string.IsNullOrWhiteSpace(actor)) { headers.Add("x-actor", actor); } } catch (Exception ex) { ex.Log(); } }
/// <summary> /// Adds the performance information if the request included the directive to do so. /// </summary> /// <param name="context"> /// The context of the current API call. /// </param> /// <param name="queryString"> /// The query string for the URL that invoked the current API request. /// </param> /// <param name="responseHeaders"> /// The response headers for the API call being processed. /// </param> internal static void AddPerformanceInformation(CommerceContext context, string queryString, HttpResponseHeaders responseHeaders) { Stopwatch callTimer = (Stopwatch)context[Key.CallTimer]; callTimer.Stop(); context.PerformanceInformation.Add("Total", String.Format("{0} ms", callTimer.ElapsedMilliseconds)); NameValueCollection queryStringItems = HttpUtility.ParseQueryString(queryString); if (queryStringItems["analytics"] == "1") { responseHeaders.Add("x-analytics", context.PerformanceInformation.Collate()); } }
public static void FillFromHeaderCollection(this HttpResponseHeaders headers, HeaderCollection targetHeaders) { if (headers == null) { throw new ArgumentNullException(nameof(headers)); } if (targetHeaders == null) { throw new ArgumentNullException(nameof(targetHeaders)); } foreach (var kv in targetHeaders) { headers.Add(kv.Key, kv.Value); } }
internal static void SetCookie(this HttpResponseHeaders headers, Cookie cookie) { var cookieBuilder = new StringBuilder(HttpUtility.UrlEncode(cookie.Name) + "=" + HttpUtility.UrlEncode(cookie.Value)); if (cookie.HttpOnly) { cookieBuilder.Append("; HttpOnly"); } if (cookie.Secure) { cookieBuilder.Append("; Secure"); } headers.Add("Set-Cookie", cookieBuilder.ToString()); }
/// <summary> /// HttpResponse can have 2 headers. These headers have restrictions on what values are allowed. /// This optimizes to combine the 2 headers without iterating overall of them to duplicate it into a new /// header object. /// </summary> /// <param name="responseHeaders"></param> /// <param name="httpContentHeaders"></param> public HttpResponseHeadersWrapper( HttpResponseHeaders responseHeaders, HttpContentHeaders httpContentHeaders) { if (responseHeaders.TryGetValues(HttpConstants.HttpHeaders.OwnerFullName, out IEnumerable <string> values)) { responseHeaders.Remove(HttpConstants.HttpHeaders.OwnerFullName); foreach (string val in values) { responseHeaders.Add(HttpConstants.HttpHeaders.OwnerFullName, Uri.UnescapeDataString(val)); } } this.httpResponseHeaders = responseHeaders; this.httpContentHeaders = httpContentHeaders; this.dictionaryNameValueCollection = new Lazy <DictionaryNameValueCollection>(() => new DictionaryNameValueCollection()); }
public static void SetCookie(this HttpResponseHeaders headers, Cookie cookie) { headers.CheckNotNull(nameof(headers)); cookie.CheckNotNull(nameof(cookie)); var cookieBuilder = new StringBuilder(HttpUtility.UrlEncode(cookie.Name) + "=" + HttpUtility.UrlEncode(cookie.Value)); if (cookie.HttpOnly) { cookieBuilder.Append("; HttpOnly"); } if (cookie.Secure) { cookieBuilder.Append("; Secure"); } headers.Add("Set-Cookie", cookieBuilder.ToString()); }
/// <summary> /// Creates a new response message /// </summary> /// <param name="headers">The headers.</param> private void AddAnonymHeader(HttpResponseHeaders headers) { Debug.Assert(headers != null); Guid?anonymId; if (Result == null) { anonymId = GetAnonymId(); } else { anonymId = Result.AnonymId; } if (anonymId != null) { headers.Add(ResourceKeys.AnonymIdCookieName, anonymId.Value.ToString()); } }
public static void SetCookie(this HttpResponseHeaders headers, Cookie cookie) { //Check.NotNull(headers, nameof(headers)); //Check.NotNull(cookie, nameof(cookie)); if (headers == null || cookie == null) { throw new ArgumentNullException("HttpResponseHeaders Or cookie"); } var cookieBuilder = new StringBuilder(HttpUtility.UrlEncode(cookie.Name) + "=" + HttpUtility.UrlEncode(cookie.Value)); if (cookie.HttpOnly) { cookieBuilder.Append("; HttpOnly"); } if (cookie.Secure) { cookieBuilder.Append("; Secure"); } headers.Add("Set-Cookie", cookieBuilder.ToString()); }
/// <summary> /// Insert a response HTTP header /// </summary> /// <param name="header">A <see cref="System.Net.Http.Headers.HttpResponseHeaders"/> object on wich the response header will be recorded.</param> /// <param name="name">The header attribute name.</param> /// <param name="value">The header attribute value.</param> public void AddResponseHeader(HttpResponseHeaders header, string name, string value) { if (name.Equals("Age", StringComparison.OrdinalIgnoreCase)) { header.Age = TimeSpan.Parse(value); } else if (name.Equals("Cache-Control", StringComparison.OrdinalIgnoreCase)) { header.CacheControl = CacheControlHeaderValue.Parse(value); } else if (name.Equals("Date", StringComparison.OrdinalIgnoreCase)) { header.Date = DateTimeOffset.Parse(value); } else if (name.Equals("ETag", StringComparison.OrdinalIgnoreCase)) { header.ETag = EntityTagHeaderValue.Parse(value); } else if (name.Equals("Location", StringComparison.OrdinalIgnoreCase)) { header.Location = new Uri(value); } else if (name.Equals("Retry-After", StringComparison.OrdinalIgnoreCase)) { header.RetryAfter = RetryConditionHeaderValue.Parse(value); } else { header.Add(name, value); } }
private static void AddResponseHeaders(HttpResponseHeaders headers) { headers.Add("x-api-version", _versionNumber); headers.Add("x-api-build", _buildNumber); }
public void Headers() { HttpResponseMessage message = new HttpResponseMessage(); HttpResponseHeaders headers = message.Headers; headers.AcceptRanges.Add("ac-v"); headers.Age = TimeSpan.MaxValue; headers.CacheControl = new CacheControlHeaderValue() { MaxStale = true }; headers.Connection.Add("test-value"); headers.ConnectionClose = true; headers.Date = new DateTimeOffset(DateTime.Today); headers.ETag = new EntityTagHeaderValue("\"tag\"", true); headers.Location = new Uri("http://xamarin.com"); headers.Pragma.Add(new NameValueHeaderValue("name", "value")); headers.ProxyAuthenticate.Add(new AuthenticationHeaderValue("proxy", "par")); headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.MinValue); headers.Server.Add(new ProductInfoHeaderValue("(comment)")); headers.Trailer.Add("trailer-vvv"); headers.TransferEncoding.Add(new TransferCodingHeaderValue("tchv")); headers.TransferEncodingChunked = true; headers.Upgrade.Add(new ProductHeaderValue("prod", "ver")); headers.Vary.Add("vary"); headers.Via.Add(new ViaHeaderValue("protocol", "rec-by")); headers.Warning.Add(new WarningHeaderValue(5, "agent", "\"txt\"")); headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("www", "par")); try { headers.Add("age", ""); Assert.Fail("age"); } catch (FormatException) { } try { headers.Add("date", ""); Assert.Fail("date"); } catch (FormatException) { } try { headers.Add("etag", ""); Assert.Fail("etag"); } catch (FormatException) { } try { headers.Add("location", "extra"); Assert.Fail("location"); } catch (FormatException) { } try { headers.Add("retry-after", "extra"); Assert.Fail("retry-after"); } catch (FormatException) { } headers.Add("accept-ranges", "achs"); // TODO: headers.Add ("cache-control", "cache-value"); headers.Add("connection", "ccc"); headers.Add("pragma", "p"); headers.Add("proxy-authenticate", "ttt"); headers.Add("server", "server"); headers.Add("trailer", "tt-r"); headers.Add("transfer-encoding", "ttt"); headers.Add("upgrade", "uuu"); headers.Add("upgrade", "vvvvaa"); headers.Add("vary", "vvaar"); headers.Add("via", "prot v"); headers.Add("warning", "4 ww \"t\""); headers.Add("www-Authenticate", "ww"); Assert.IsTrue(headers.AcceptRanges.SequenceEqual( new[] { "ac-v", "achs" } )); Assert.AreEqual(TimeSpan.MaxValue, headers.Age); Assert.AreEqual( new CacheControlHeaderValue() { MaxStale = true, // TODO Extensions = { new NameValueHeaderValue ("cache-value") } }, headers.CacheControl); Assert.IsTrue(headers.Connection.SequenceEqual( new string[] { "test-value", "close", "ccc" })); Assert.AreEqual(new DateTimeOffset(DateTime.Today), headers.Date); Assert.AreEqual(new EntityTagHeaderValue("\"tag\"", true), headers.ETag); Assert.AreEqual(new Uri("http://xamarin.com"), headers.Location); Assert.IsTrue(headers.Pragma.SequenceEqual( new [] { new NameValueHeaderValue("name", "value"), new NameValueHeaderValue("p"), })); Assert.IsTrue(headers.ProxyAuthenticate.SequenceEqual( new [] { new AuthenticationHeaderValue("proxy", "par"), new AuthenticationHeaderValue("ttt") } )); Assert.AreEqual(new RetryConditionHeaderValue(TimeSpan.MinValue), headers.RetryAfter); Assert.IsTrue(headers.Server.SequenceEqual( new [] { new ProductInfoHeaderValue("(comment)"), new ProductInfoHeaderValue(new ProductHeaderValue("server")) } )); Assert.IsTrue(headers.Trailer.SequenceEqual( new [] { "trailer-vvv", "tt-r" })); Assert.IsTrue(headers.TransferEncoding.SequenceEqual( new[] { new TransferCodingHeaderValue("tchv"), new TransferCodingHeaderValue("chunked"), new TransferCodingHeaderValue("ttt") } )); Assert.IsTrue(headers.Upgrade.SequenceEqual( new[] { new ProductHeaderValue("prod", "ver"), new ProductHeaderValue("uuu"), new ProductHeaderValue("vvvvaa") } )); Assert.IsTrue(headers.Vary.SequenceEqual( new[] { "vary", "vvaar" } )); Assert.IsTrue(headers.Via.SequenceEqual( new[] { new ViaHeaderValue("protocol", "rec-by"), new ViaHeaderValue("prot", "v") } )); Assert.IsTrue(headers.Warning.SequenceEqual( new[] { new WarningHeaderValue(5, "agent", "\"txt\""), new WarningHeaderValue(4, "ww", "\"t\"") } )); Assert.IsTrue(headers.WwwAuthenticate.SequenceEqual( new[] { new AuthenticationHeaderValue("www", "par"), new AuthenticationHeaderValue("ww") } )); }
public void Headers_Invalid() { HttpResponseMessage message = new HttpResponseMessage(); HttpResponseHeaders headers = message.Headers; try { headers.Add("age", ""); Assert.Fail("#1"); } catch (FormatException) { } try { headers.Add(null, ""); Assert.Fail("#2"); } catch (ArgumentException) { } try { headers.Add("mm", null as IEnumerable <string>); Assert.Fail("#2b"); } catch (ArgumentNullException) { } try { headers.Add("Allow", "audio"); Assert.Fail("#2c"); } catch (InvalidOperationException) { } Assert.IsFalse(headers.TryAddWithoutValidation("Allow", ""), "#3"); Assert.IsFalse(headers.TryAddWithoutValidation(null, ""), "#4"); try { headers.Contains(null); Assert.Fail("#5"); } catch (ArgumentException) { } try { headers.GetValues(null); Assert.Fail("#6a"); } catch (ArgumentException) { } try { headers.GetValues("bbbb"); Assert.Fail("#6b"); } catch (InvalidOperationException) { } try { headers.Add("location", new[] { "google.com", "xamarin.com" }); Assert.Fail("#7a"); } catch (FormatException) { } headers.TryAddWithoutValidation("location", "*****@*****.**"); try { headers.Add("location", "w3.org"); Assert.Fail("#7b"); } catch (FormatException) { } }
public void Location_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { // just verify header names are compared using case-insensitive comparison. headers.TryAddWithoutValidation("LoCaTiOn", " http://www.example.com/path/?q=v "); Assert.Equal(new Uri("http://www.example.com/path/?q=v"), headers.Location); headers.Clear(); headers.TryAddWithoutValidation("Location", "http://host"); Assert.Equal(new Uri("http://host"), headers.Location); // This violates the RFCs, the Location header should be absolute. However, // IIS and HttpListener do not enforce this requirement. headers.Clear(); headers.Add("LoCaTiOn", "/relative/"); Assert.Equal <Uri>(new Uri("/relative/", UriKind.Relative), headers.Location); }