views:

296

answers:

1

There is a local service from which I need to consume a generated XML Document Stream. Though the end point is not a REST service per se. I wanted to be sure the method I've outlined below is the most efficient way of getting the response returned into an XDocument.

Uri requestUri = null;
Uri.TryCreate(String.Format(SearchAddress, filter),
    UriKind.Absolute, out requestUri);

NetworkCredential nc =
    new NetworkCredential("Login", "Password");
CredentialCache cCache = new CredentialCache();
cCache.Add(requestUri, "Basic", nc);

HttpWebRequest request =
    (HttpWebRequest)HttpWebRequest.Create(requestUri);
request.Credentials = cCache;
request.PreAuthenticate = true;
request.Method = WebRequestMethods.Http.Get;

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
XDocument xDoc =
    XDocument.Load(new StreamReader(response.GetResponseStream()));
+1  A: 

If you want a synchronous request then in my opinion yes it is.

But it would be a good idea to handle WebException. In WebException.Response.GetResponseStream() you should have either a HTTP/HTML error page or a soapfault.

Asynch request
// starts asynch retrieval of response stream...
var result = request.BeginGetResponse(...)
// setting a timeout callback method, BeginGetResponse doesn´t timeout...
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, ...)

Jens Granlund
Good idea about handling `WebException`. That said, what would your suggested modification be for an asynchronous request?
ahsteele