void GotResponse(IAsyncResult result) { HttpChannelRequestAsyncResult channelResult = (HttpChannelRequestAsyncResult)result.AsyncState; channelResult.CompletedSynchronously &= result.CompletedSynchronously; WebResponse res; Stream resstr; try { res = web_request.EndGetResponse(result); resstr = res.GetResponseStream(); } catch (WebException we) { res = we.Response; try { // The response might contain SOAP fault. It might not. resstr = res.GetResponseStream(); } catch (WebException we2) { channelResult.Complete(we2); return; } } try { using (var responseStream = resstr) { MemoryStream ms = new MemoryStream(); byte [] b = new byte [65536]; int n = 0; while (true) { n = responseStream.Read(b, 0, 65536); if (n == 0) { break; } ms.Write(b, 0, n); } ms.Seek(0, SeekOrigin.Begin); channelResult.Response = Encoder.ReadMessage( //responseStream, MaxSizeOfHeaders); ms, MaxSizeOfHeaders, res.ContentType); /* * MessageBuffer buf = ret.CreateBufferedCopy (0x10000); * ret = buf.CreateMessage (); * System.Xml.XmlTextWriter w = new System.Xml.XmlTextWriter (Console.Out); * w.Formatting = System.Xml.Formatting.Indented; * buf.CreateMessage ().WriteMessage (w); * w.Close (); */ channelResult.Complete(); } } catch (Exception ex) { channelResult.Complete(ex); } finally { res.Close(); } }
public override IAsyncResult BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, object state) { ThrowIfDisposedOrNotOpen(); HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult(message, timeout, this, callback, state); BeginProcessRequest(result); return(result); }
public override Message EndRequest(IAsyncResult result) { if (result == null) { throw new ArgumentNullException("result"); } HttpChannelRequestAsyncResult r = result as HttpChannelRequestAsyncResult; if (r == null) { throw new InvalidOperationException("Wrong IAsyncResult"); } r.WaitEnd(); return(r.Response); }
void BeginProcessRequest(HttpChannelRequestAsyncResult result) { Message message = result.Message; TimeSpan timeout = result.Timeout; // FIXME: is distination really like this? Uri destination = message.Headers.To; if (destination == null) { if (source.Transport.ManualAddressing) { throw new InvalidOperationException("When manual addressing is enabled on the transport, every request messages must be set its destination address."); } else { destination = Via ?? RemoteAddress.Uri; } } var web_request = HttpWebRequest.Create(destination); web_requests.Add(web_request); result.WebRequest = web_request; web_request.Method = "POST"; web_request.ContentType = Encoder.ContentType; #if NET_2_1 HttpWebRequest hwr = (web_request as HttpWebRequest); #if MOONLIGHT if (hwr.SupportsCookieContainer) { #endif var cmgr = source.GetProperty <IHttpCookieContainerManager> (); if (cmgr != null) { hwr.CookieContainer = cmgr.CookieContainer; } #if MOONLIGHT } #endif #endif #if !MOONLIGHT // until we support NetworkCredential like SL4 will do. // client authentication (while SL3 has NetworkCredential class, it is not implemented yet. So, it is non-SL only.) var httpbe = (HttpTransportBindingElement)source.Transport; string authType = null; switch (httpbe.AuthenticationScheme) { // AuthenticationSchemes.Anonymous is the default, ignored. case AuthenticationSchemes.Basic: authType = "Basic"; break; case AuthenticationSchemes.Digest: authType = "Digest"; break; case AuthenticationSchemes.Ntlm: authType = "Ntlm"; break; case AuthenticationSchemes.Negotiate: authType = "Negotiate"; break; } if (authType != null) { var cred = source.ClientCredentials; string user = cred != null ? cred.UserName.UserName : null; string pwd = cred != null ? cred.UserName.Password : null; if (String.IsNullOrEmpty(user)) { throw new InvalidOperationException(String.Format("Use ClientCredentials to specify a user name for required HTTP {0} authentication.", authType)); } var nc = new NetworkCredential(user, pwd); web_request.Credentials = nc; // FIXME: it is said required in SL4, but it blocks full WCF. //web_request.UseDefaultCredentials = false; } #endif #if !NET_2_1 // FIXME: implement this to not depend on Timeout property web_request.Timeout = (int)timeout.TotalMilliseconds; #endif // There is no SOAP Action/To header when AddressingVersion is None. if (message.Version.Envelope.Equals(EnvelopeVersion.Soap11) || message.Version.Addressing.Equals(AddressingVersion.None)) { if (message.Headers.Action != null) { web_request.Headers ["SOAPAction"] = String.Concat("\"", message.Headers.Action, "\""); message.Headers.RemoveAll("Action", message.Version.Addressing.Namespace); } } // apply HttpRequestMessageProperty if exists. bool suppressEntityBody = false; string pname = HttpRequestMessageProperty.Name; if (message.Properties.ContainsKey(pname)) { HttpRequestMessageProperty hp = (HttpRequestMessageProperty)message.Properties [pname]; #if !NET_2_1 // FIXME: how can this be done? foreach (var key in hp.Headers.AllKeys) { if (!WebHeaderCollection.IsRestricted(key)) { web_request.Headers [key] = hp.Headers [key]; } } #endif web_request.Method = hp.Method; // FIXME: do we have to handle hp.QueryString ? if (hp.SuppressEntityBody) { suppressEntityBody = true; } } #if !NET_2_1 if (source.ClientCredentials.ClientCertificate.Certificate != null) { ((HttpWebRequest)web_request).ClientCertificates.Add(source.ClientCredentials.ClientCertificate.Certificate); } #endif if (!suppressEntityBody && String.Compare(web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) { MemoryStream buffer = new MemoryStream(); Encoder.WriteMessage(message, buffer); if (buffer.Length > int.MaxValue) { throw new InvalidOperationException("The argument message is too large."); } #if !NET_2_1 web_request.ContentLength = (int)buffer.Length; #endif web_request.BeginGetRequestStream(delegate(IAsyncResult r) { try { result.CompletedSynchronously &= r.CompletedSynchronously; using (Stream s = web_request.EndGetRequestStream(r)) s.Write(buffer.GetBuffer(), 0, (int)buffer.Length); web_request.BeginGetResponse(GotResponse, result); } catch (WebException ex) { switch (ex.Status) { #if !NET_2_1 case WebExceptionStatus.NameResolutionFailure: #endif case WebExceptionStatus.ConnectFailure: result.Complete(new EndpointNotFoundException(new EndpointNotFoundException().Message, ex)); break; default: result.Complete(ex); break; } } catch (Exception ex) { result.Complete(ex); } }, null); } else { web_request.BeginGetResponse(GotResponse, result); } }
void GotResponse(IAsyncResult result) { HttpChannelRequestAsyncResult channelResult = (HttpChannelRequestAsyncResult)result.AsyncState; channelResult.CompletedSynchronously &= result.CompletedSynchronously; WebResponse res; Stream resstr; try { res = channelResult.WebRequest.EndGetResponse(result); resstr = res.GetResponseStream(); } catch (WebException we) { res = we.Response; if (res == null) { channelResult.Complete(we); return; } var hrr2 = (HttpWebResponse)res; if ((int)hrr2.StatusCode >= 400 && (int)hrr2.StatusCode < 500) { Exception exception = new WebException( String.Format("There was an error on processing web request: Status code {0}({1}): {2}", (int)hrr2.StatusCode, hrr2.StatusCode, hrr2.StatusDescription), null, WebExceptionStatus.ProtocolError, hrr2); if ((int)hrr2.StatusCode == 404) { // Throw the same exception .NET does exception = new EndpointNotFoundException( "There was no endpoint listening at {0} that could accept the message. This is often caused by an incorrect address " + "or SOAP action. See InnerException, if present, for more details.", exception); } channelResult.Complete(exception); return; } try { // The response might contain SOAP fault. It might not. resstr = res.GetResponseStream(); } catch (WebException we2) { channelResult.Complete(we2); return; } } var hrr = (HttpWebResponse)res; if ((int)hrr.StatusCode >= 400 && (int)hrr.StatusCode < 500) { channelResult.Complete(new WebException(String.Format("There was an error on processing web request: Status code {0}({1}): {2}", (int)hrr.StatusCode, hrr.StatusCode, hrr.StatusDescription))); } try { Message ret; // TODO: unit test to make sure an empty response never throws // an exception at this level if (hrr.ContentLength == 0) { ret = Message.CreateMessage(Encoder.MessageVersion, String.Empty); } else { using (var responseStream = resstr) { MemoryStream ms = new MemoryStream(); byte [] b = new byte [65536]; int n = 0; while (true) { n = responseStream.Read(b, 0, 65536); if (n == 0) { break; } ms.Write(b, 0, n); } ms.Seek(0, SeekOrigin.Begin); ret = Encoder.ReadMessage( ms, (int)source.Transport.MaxReceivedMessageSize, res.ContentType); } } var rp = new HttpResponseMessageProperty() { StatusCode = hrr.StatusCode, StatusDescription = hrr.StatusDescription }; #if MOONLIGHT if (hrr.SupportsHeaders) { foreach (string key in hrr.Headers) { rp.Headers [key] = hrr.Headers [key]; } } #else foreach (var key in hrr.Headers.AllKeys) { rp.Headers [key] = hrr.Headers [key]; } #endif ret.Properties.Add(HttpResponseMessageProperty.Name, rp); channelResult.Response = ret; channelResult.Complete(); } catch (Exception ex) { channelResult.Complete(ex); } finally { res.Close(); } }
void BeginProcessRequest (HttpChannelRequestAsyncResult result) { Message message = result.Message; TimeSpan timeout = result.Timeout; // FIXME: is distination really like this? Uri destination = message.Headers.To; if (destination == null) { if (source.Transport.ManualAddressing) throw new InvalidOperationException ("When manual addressing is enabled on the transport, every request messages must be set its destination address."); else destination = Via ?? RemoteAddress.Uri; } var web_request = HttpWebRequest.Create (destination); web_requests.Add (web_request); result.WebRequest = web_request; web_request.Method = "POST"; web_request.ContentType = Encoder.ContentType; #if NET_2_1 HttpWebRequest hwr = (web_request as HttpWebRequest); #if MOONLIGHT if (hwr.SupportsCookieContainer) { #endif var cmgr = source.GetProperty<IHttpCookieContainerManager> (); if (cmgr != null) hwr.CookieContainer = cmgr.CookieContainer; #if MOONLIGHT } #endif #endif #if !MOONLIGHT // until we support NetworkCredential like SL4 will do. // client authentication (while SL3 has NetworkCredential class, it is not implemented yet. So, it is non-SL only.) var httpbe = (HttpTransportBindingElement) source.Transport; string authType = null; switch (httpbe.AuthenticationScheme) { // AuthenticationSchemes.Anonymous is the default, ignored. case AuthenticationSchemes.Basic: authType = "Basic"; break; case AuthenticationSchemes.Digest: authType = "Digest"; break; case AuthenticationSchemes.Ntlm: authType = "Ntlm"; break; case AuthenticationSchemes.Negotiate: authType = "Negotiate"; break; } if (authType != null) { var cred = source.ClientCredentials; string user = cred != null ? cred.UserName.UserName : null; string pwd = cred != null ? cred.UserName.Password : null; if (String.IsNullOrEmpty (user)) throw new InvalidOperationException (String.Format ("Use ClientCredentials to specify a user name for required HTTP {0} authentication.", authType)); var nc = new NetworkCredential (user, pwd); web_request.Credentials = nc; // FIXME: it is said required in SL4, but it blocks full WCF. //web_request.UseDefaultCredentials = false; } #endif #if !NET_2_1 // FIXME: implement this to not depend on Timeout property web_request.Timeout = (int) timeout.TotalMilliseconds; #endif // There is no SOAP Action/To header when AddressingVersion is None. if (message.Version.Envelope.Equals (EnvelopeVersion.Soap11) || message.Version.Addressing.Equals (AddressingVersion.None)) { if (message.Headers.Action != null) { web_request.Headers ["SOAPAction"] = String.Concat ("\"", message.Headers.Action, "\""); message.Headers.RemoveAll ("Action", message.Version.Addressing.Namespace); } } // apply HttpRequestMessageProperty if exists. bool suppressEntityBody = false; #if !NET_2_1 string pname = HttpRequestMessageProperty.Name; if (message.Properties.ContainsKey (pname)) { HttpRequestMessageProperty hp = (HttpRequestMessageProperty) message.Properties [pname]; web_request.Headers.Clear (); web_request.Headers.Add (hp.Headers); web_request.Method = hp.Method; // FIXME: do we have to handle hp.QueryString ? if (hp.SuppressEntityBody) suppressEntityBody = true; } #endif if (!suppressEntityBody && String.Compare (web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) { MemoryStream buffer = new MemoryStream (); Encoder.WriteMessage (message, buffer); if (buffer.Length > int.MaxValue) throw new InvalidOperationException ("The argument message is too large."); #if !NET_2_1 web_request.ContentLength = (int) buffer.Length; #endif web_request.BeginGetRequestStream (delegate (IAsyncResult r) { try { result.CompletedSynchronously &= r.CompletedSynchronously; using (Stream s = web_request.EndGetRequestStream (r)) s.Write (buffer.GetBuffer (), 0, (int) buffer.Length); web_request.BeginGetResponse (GotResponse, result); } catch (WebException ex) { switch (ex.Status) { #if !NET_2_1 case WebExceptionStatus.NameResolutionFailure: #endif case WebExceptionStatus.ConnectFailure: result.Complete (new EndpointNotFoundException (new EndpointNotFoundException ().Message, ex)); break; default: result.Complete (ex); break; } } catch (Exception ex) { result.Complete (ex); } }, null); } else { web_request.BeginGetResponse (GotResponse, result); } }
public override IAsyncResult BeginRequest (Message message, TimeSpan timeout, AsyncCallback callback, object state) { ThrowIfDisposedOrNotOpen (); HttpChannelRequestAsyncResult result = new HttpChannelRequestAsyncResult (message, timeout, this, callback, state); BeginProcessRequest (result); return result; }
void BeginProcessRequest(HttpChannelRequestAsyncResult result) { Message message = result.Message; TimeSpan timeout = result.Timeout; // FIXME: is distination really like this? Uri destination = message.Headers.To; if (destination == null) { if (source.Source.ManualAddressing) { throw new InvalidOperationException("When manual addressing is enabled on the transport, every request messages must be set its destination address."); } else { destination = Via ?? RemoteAddress.Uri; } } web_request = HttpWebRequest.Create(destination); web_request.Method = "POST"; web_request.ContentType = Encoder.ContentType; #if !NET_2_1 // FIXME: implement this to not depend on Timeout property web_request.Timeout = (int)timeout.TotalMilliseconds; #endif // There is no SOAP Action/To header when AddressingVersion is None. if (message.Version.Envelope.Equals(EnvelopeVersion.Soap11) || message.Version.Addressing.Equals(AddressingVersion.None)) { if (message.Headers.Action != null) { web_request.Headers ["SOAPAction"] = String.Concat("\"", message.Headers.Action, "\""); message.Headers.RemoveAll("Action", message.Version.Addressing.Namespace); } } // apply HttpRequestMessageProperty if exists. bool suppressEntityBody = false; #if !NET_2_1 string pname = HttpRequestMessageProperty.Name; if (message.Properties.ContainsKey(pname)) { HttpRequestMessageProperty hp = (HttpRequestMessageProperty)message.Properties [pname]; web_request.Headers.Add(hp.Headers); web_request.Method = hp.Method; // FIXME: do we have to handle hp.QueryString ? if (hp.SuppressEntityBody) { suppressEntityBody = true; } } #endif if (!suppressEntityBody && String.Compare(web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) { MemoryStream buffer = new MemoryStream(); Encoder.WriteMessage(message, buffer); if (buffer.Length > int.MaxValue) { throw new InvalidOperationException("The argument message is too large."); } #if !NET_2_1 web_request.ContentLength = (int)buffer.Length; #endif web_request.BeginGetRequestStream(delegate(IAsyncResult r) { try { result.CompletedSynchronously &= r.CompletedSynchronously; using (Stream s = web_request.EndGetRequestStream(r)) s.Write(buffer.GetBuffer(), 0, (int)buffer.Length); web_request.BeginGetResponse(GotResponse, result); } catch (Exception ex) { result.Complete(ex); } }, null); } else { web_request.BeginGetResponse(GotResponse, result); } }
/// <summary> /// Inicia o processamento da requisição. /// </summary> /// <param name="result">Resultado assincrono.</param> void BeginProcessRequest(HttpChannelRequestAsyncResult result) { Message message = result.Message; TimeSpan timeout = result.Timeout; Uri destination = message.Headers.To; if (destination == null) { if (source.Transport.ManualAddressing) { throw new InvalidOperationException("When manual addressing is enabled on the transport, every request messages must be set its destination address."); } else { destination = Via ?? RemoteAddress.Uri; } } var web_request = (HttpWebRequest)HttpWebRequest.Create(destination); web_requests.Add(web_request); result.WebRequest = web_request; web_request.Method = "POST"; web_request.ContentType = Encoder.ContentType; HttpWebRequest hwr = (web_request as HttpWebRequest); var cmgr = source.GetProperty <IHttpCookieContainerManager>(); if (cmgr != null) { hwr.CookieContainer = cmgr.CookieContainer; } var httpbe = (HttpTransportBindingElement)source.Transport; string authType = null; switch (httpbe.AuthenticationScheme) { case AuthenticationSchemes.Basic: authType = "Basic"; break; case AuthenticationSchemes.Digest: authType = "Digest"; break; case AuthenticationSchemes.Ntlm: authType = "Ntlm"; break; case AuthenticationSchemes.Negotiate: authType = "Negotiate"; break; } if (authType != null) { var cred = source.ClientCredentials; string user = cred != null ? cred.UserName.UserName : null; string pwd = cred != null ? cred.UserName.Password : null; if (String.IsNullOrEmpty(user)) { throw new InvalidOperationException(String.Format("Use ClientCredentials to specify a user name for required HTTP {0} authentication.", authType)); } var nc = new NetworkCredential(user, pwd); web_request.Credentials = nc; } web_request.Timeout = (int)timeout.TotalMilliseconds; if (message.Version.Envelope.Equals(EnvelopeVersion.Soap11) || message.Version.Addressing.Equals(AddressingVersion.None)) { if (message.Headers.Action != null) { web_request.Headers["SOAPAction"] = String.Concat("\"", message.Headers.Action, "\""); } } bool suppressEntityBody = false; string pname = HttpRequestMessageProperty.Name; if (message.Properties.ContainsKey(pname)) { HttpRequestMessageProperty hp = (HttpRequestMessageProperty)message.Properties[pname]; foreach (var key in hp.Headers.AllKeys) { if (WebHeaderCollection.IsRestricted(key)) { switch (key) { case "Accept": web_request.Accept = hp.Headers[key]; break; case "Connection": web_request.Connection = hp.Headers[key]; break; case "ContentType": web_request.ContentType = hp.Headers[key]; break; case "Expect": web_request.Expect = hp.Headers[key]; break; case "Host": web_request.Host = hp.Headers[key]; break; case "Referer": web_request.Referer = hp.Headers[key]; break; case "Transfer-Encoding": web_request.TransferEncoding = hp.Headers[key]; break; case "User-Agent": web_request.UserAgent = hp.Headers[key]; break; } } else { web_request.Headers[key] = hp.Headers[key]; } } web_request.Method = hp.Method; if (hp.SuppressEntityBody) { suppressEntityBody = true; } } #if !NET_2_1 if (source.ClientCredentials != null) { var cred = source.ClientCredentials; if ((cred.ClientCertificate != null) && (cred.ClientCertificate.Certificate != null)) { ((HttpWebRequest)web_request).ClientCertificates.Add(cred.ClientCertificate.Certificate); } } #endif if (!suppressEntityBody && String.Compare(web_request.Method, "GET", StringComparison.OrdinalIgnoreCase) != 0) { var buffer = new System.IO.MemoryStream(); Encoder.WriteMessage(message, buffer); if (buffer.Length > int.MaxValue) { throw new InvalidOperationException("The argument message is too large."); } web_request.ContentLength = (int)buffer.Length; var getRequestStreamCallback = new AsyncCallback(r => { try { result.CompletedSynchronously &= r.CompletedSynchronously; using (var s = web_request.EndGetRequestStream(r)) s.Write(buffer.GetBuffer(), 0, (int)buffer.Length); web_request.BeginGetResponse(GotResponse, result); } catch (WebException ex) { switch (ex.Status) { case WebExceptionStatus.NameResolutionFailure: case WebExceptionStatus.ConnectFailure: result.Complete(new EndpointNotFoundException(new EndpointNotFoundException().Message, ex)); break; default: result.Complete(ex); break; } } catch (Exception ex) { result.Complete(ex); } }); if (Colosoft.Runtime.PlatformHelper.IsRunningOnMono) { Colosoft.Net.Mono.HttpWebRequestExtensions.BeginGetRequestStream(web_request, getRequestStreamCallback, null); } else { web_request.BeginGetRequestStream(getRequestStreamCallback, null); } } else { web_request.BeginGetResponse(GotResponse, result); } }