/// <summary> /// Gets an offline snapshot version of this instance. /// </summary> /// <param name="maximumBytesToCache">The maximum bytes from the response stream to cache.</param> /// <returns>A snapshot version of this instance.</returns> /// <remarks> /// If this instance is a <see cref="NetworkDirectWebResponse"/> creating a snapshot /// will automatically close and dispose of the underlying response stream. /// If this instance is a <see cref="CachedDirectWebResponse"/>, the result will /// be the self same instance. /// </remarks> internal override CachedDirectWebResponse GetSnapshot(int maximumBytesToCache) { ErrorUtilities.VerifyOperation(!this.streamReadBegun, "Network stream reading has already begun."); this.streamReadBegun = true; var result = new CachedDirectWebResponse(this.RequestUri, this.httpWebResponse, maximumBytesToCache); this.Dispose(); return(result); }
public void DirectResponsesReceivedAsKeyValueForm() { var fields = new Dictionary<string, string> { { "var1", "value1" }, { "var2", "value2" }, }; var response = new CachedDirectWebResponse { CachedResponseStream = new MemoryStream(KeyValueFormEncoding.GetBytes(fields)), }; Assert.IsTrue(MessagingUtilities.AreEquivalent(fields, this.accessor.ReadFromResponseCore(response))); }
internal void RegisterMockNotFound(Uri requestUri) { CachedDirectWebResponse errorResponse = new CachedDirectWebResponse( requestUri, requestUri, new WebHeaderCollection(), HttpStatusCode.NotFound, "text/plain", Encoding.UTF8.WebName, new MemoryStream(Encoding.UTF8.GetBytes("Not found."))); this.RegisterMockResponse(errorResponse); }
public IncomingWebResponse GetResponse(HttpWebRequest request, DirectWebRequestOptions options) { // This request MAY have already been prepared by GetRequestStream, but // we have no guarantee, so do it just to be safe. this.PrepareRequest(request, false); // Since we may require SSL for every redirect, we handle each redirect manually // in order to detect and fail if any redirect sends us to an HTTP url. // We COULD allow automatic redirect in the cases where HTTPS is not required, // but our mock request infrastructure can't do redirects on its own either. Uri originalRequestUri = request.RequestUri; int i; for (i = 0; i < this.MaximumRedirections; i++) { this.EnsureAllowableRequestUri(request.RequestUri, (options & DirectWebRequestOptions.RequireSsl) != 0); CachedDirectWebResponse response = this.chainedWebRequestHandler.GetResponse(request, options & ~DirectWebRequestOptions.RequireSsl).GetSnapshot(this.MaximumBytesToRead); if (response.Status == HttpStatusCode.MovedPermanently || response.Status == HttpStatusCode.Redirect || response.Status == HttpStatusCode.RedirectMethod || response.Status == HttpStatusCode.RedirectKeepVerb) { // We have no copy of the post entity stream to repeat on our manually // cloned HttpWebRequest, so we have to bail. ErrorUtilities.VerifyProtocol(request.Method != "POST", MessagingStrings.UntrustedRedirectsOnPOSTNotSupported); Uri redirectUri = new Uri(response.FinalUri, response.Headers[HttpResponseHeader.Location]); request = request.Clone(redirectUri); } else { if (response.FinalUri != request.RequestUri) { // Since we don't automatically follow redirects, there's only one scenario where this // can happen: when the server sends a (non-redirecting) Content-Location header in the response. // It's imperative that we do not trust that header though, so coerce the FinalUri to be // what we just requested. Logger.Http.WarnFormat("The response from {0} included an HTTP header indicating it's the same as {1}, but it's not a redirect so we won't trust that.", request.RequestUri, response.FinalUri); response.FinalUri = request.RequestUri; } return(response); } } throw ErrorUtilities.ThrowProtocol(MessagingStrings.TooManyRedirects, originalRequestUri); }
/// <summary> /// Initializes a new instance of the <see cref="DiscoveryResult"/> class. /// </summary> /// <param name="requestUri">The user-supplied identifier.</param> /// <param name="initialResponse">The initial response.</param> /// <param name="finalResponse">The final response.</param> public DiscoveryResult(Uri requestUri, CachedDirectWebResponse initialResponse, CachedDirectWebResponse finalResponse) { this.RequestUri = requestUri; this.NormalizedUri = initialResponse.FinalUri; if (finalResponse == null) { this.ContentType = initialResponse.ContentType; this.ResponseText = initialResponse.GetResponseString(); this.IsXrds = this.ContentType != null && this.ContentType.MediaType == ContentTypes.Xrds; } else { this.ContentType = finalResponse.ContentType; this.ResponseText = finalResponse.GetResponseString(); this.IsXrds = true; if (initialResponse != finalResponse) { this.YadisLocation = finalResponse.RequestUri; } } }
public DirectWebResponse GetResponse(HttpWebRequest request, DirectWebRequestOptions options) { ErrorUtilities.VerifyArgumentNotNull(request, "request"); // This request MAY have already been prepared by GetRequestStream, but // we have no guarantee, so do it just to be safe. this.PrepareRequest(request, false); // Since we may require SSL for every redirect, we handle each redirect manually // in order to detect and fail if any redirect sends us to an HTTP url. // We COULD allow automatic redirect in the cases where HTTPS is not required, // but our mock request infrastructure can't do redirects on its own either. Uri originalRequestUri = request.RequestUri; int i; for (i = 0; i < this.MaximumRedirections; i++) { this.EnsureAllowableRequestUri(request.RequestUri, (options & DirectWebRequestOptions.RequireSsl) != 0); CachedDirectWebResponse response = this.chainedWebRequestHandler.GetResponse(request, options & ~DirectWebRequestOptions.RequireSsl).GetSnapshot(this.MaximumBytesToRead); if (response.Status == HttpStatusCode.MovedPermanently || response.Status == HttpStatusCode.Redirect || response.Status == HttpStatusCode.RedirectMethod || response.Status == HttpStatusCode.RedirectKeepVerb) { // We have no copy of the post entity stream to repeat on our manually // cloned HttpWebRequest, so we have to bail. ErrorUtilities.VerifyProtocol(request.Method != "POST", MessagingStrings.UntrustedRedirectsOnPOSTNotSupported); Uri redirectUri = new Uri(response.FinalUri, response.Headers[HttpResponseHeader.Location]); request = request.Clone(redirectUri); } else { return(response); } } throw ErrorUtilities.ThrowProtocol(MessagingStrings.TooManyRedirects, originalRequestUri); }
internal void RegisterMockRedirect(Uri origin, Uri redirectLocation) { var redirectionHeaders = new WebHeaderCollection { { HttpResponseHeader.Location, redirectLocation.AbsoluteUri }, }; IncomingWebResponse response = new CachedDirectWebResponse(origin, origin, redirectionHeaders, HttpStatusCode.Redirect, null, null, new MemoryStream()); this.RegisterMockResponse(response); }
private void ParameterizedRequestTest(HttpDeliveryMethods scheme) { TestDirectedMessage request = new TestDirectedMessage(MessageTransport.Direct) { Age = 15, Name = "Andrew", Location = new Uri("http://hostb/pathB"), Recipient = new Uri("http://localtest"), Timestamp = DateTime.UtcNow, HttpMethods = scheme, }; CachedDirectWebResponse rawResponse = null; this.webRequestHandler.Callback = (req) => { Assert.IsNotNull(req); HttpRequestInfo reqInfo = ConvertToRequestInfo(req, this.webRequestHandler.RequestEntityStream); Assert.AreEqual(MessagingUtilities.GetHttpVerb(scheme), reqInfo.HttpMethod); var incomingMessage = this.channel.ReadFromRequest(reqInfo) as TestMessage; Assert.IsNotNull(incomingMessage); Assert.AreEqual(request.Age, incomingMessage.Age); Assert.AreEqual(request.Name, incomingMessage.Name); Assert.AreEqual(request.Location, incomingMessage.Location); Assert.AreEqual(request.Timestamp, incomingMessage.Timestamp); var responseFields = new Dictionary<string, string> { { "age", request.Age.ToString() }, { "Name", request.Name }, { "Location", request.Location.AbsoluteUri }, { "Timestamp", XmlConvert.ToString(request.Timestamp, XmlDateTimeSerializationMode.Utc) }, }; rawResponse = new CachedDirectWebResponse(); rawResponse.SetResponse(MessagingUtilities.CreateQueryString(responseFields)); return rawResponse; }; IProtocolMessage response = this.channel.Request(request); Assert.IsNotNull(response); Assert.IsInstanceOf<TestMessage>(response); TestMessage responseMessage = (TestMessage)response; Assert.AreEqual(request.Age, responseMessage.Age); Assert.AreEqual(request.Name, responseMessage.Name); Assert.AreEqual(request.Location, responseMessage.Location); }
/// <summary> /// Gets an offline snapshot version of this instance. /// </summary> /// <param name="maximumBytesToCache">The maximum bytes from the response stream to cache.</param> /// <returns>A snapshot version of this instance.</returns> /// <remarks> /// If this instance is a <see cref="NetworkDirectWebResponse"/> creating a snapshot /// will automatically close and dispose of the underlying response stream. /// If this instance is a <see cref="CachedDirectWebResponse"/>, the result will /// be the self same instance. /// </remarks> internal override CachedDirectWebResponse GetSnapshot(int maximumBytesToCache) { ErrorUtilities.VerifyOperation(!this.streamReadBegun, "Network stream reading has already begun."); ErrorUtilities.VerifyOperation(this.httpWebResponse != null, "httpWebResponse != null"); this.streamReadBegun = true; var result = new CachedDirectWebResponse(this.RequestUri, this.httpWebResponse, maximumBytesToCache); this.Dispose(); return result; }
public void PostMultipart() { var httpHandler = new TestWebRequestHandler(); bool callbackTriggered = false; httpHandler.Callback = req => { var m = Regex.Match(req.ContentType, "multipart/form-data; boundary=(.+)"); Assert.IsTrue(m.Success, "Content-Type HTTP header not set correctly."); string boundary = m.Groups[1].Value; boundary = boundary.Substring(0, boundary.IndexOf(';')); // trim off charset string expectedEntity = "--{0}\r\nContent-Disposition: form-data; name=\"a\"\r\n\r\nb\r\n--{0}--\r\n"; expectedEntity = string.Format(expectedEntity, boundary); string actualEntity = httpHandler.RequestEntityAsString; Assert.AreEqual(expectedEntity, actualEntity); callbackTriggered = true; Assert.AreEqual(req.ContentLength, actualEntity.Length); IncomingWebResponse resp = new CachedDirectWebResponse(); return resp; }; var request = (HttpWebRequest)WebRequest.Create("http://someserver"); var parts = new[] { MultipartPostPart.CreateFormPart("a", "b"), }; request.PostMultipart(httpHandler, parts); Assert.IsTrue(callbackTriggered); }
/// <summary> /// Determines whether a given HTTP response constitutes an XRDS document. /// </summary> /// <param name="response">The response to test.</param> /// <returns> /// <c>true</c> if the response constains an XRDS document; otherwise, <c>false</c>. /// </returns> private static bool IsXrdsDocument(CachedDirectWebResponse response) { if (response.ContentType == null) { return false; } if (response.ContentType.MediaType == ContentTypes.Xrds) { return true; } if (response.ContentType.MediaType == ContentTypes.Xml) { // This COULD be an XRDS document with an imprecise content-type. response.ResponseStream.Seek(0, SeekOrigin.Begin); XmlReader reader = XmlReader.Create(response.ResponseStream); while (reader.Read() && reader.NodeType != XmlNodeType.Element) { // intentionally blank } if (reader.NamespaceURI == XrdsNode.XrdsNamespace && reader.Name == "XRDS") { return true; } } return false; }