Efficient way to get HttpWebResponse and put it in an XDocument

There is a local service from which I need to use the generated stream of XML documents. Although the endpoint is not a REST service as such. I wanted to be sure that the method described below is the most efficient way to get the response returned in 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()));
+3
source share
1 answer

If you need a synchronous request, then, in my opinion, yes.

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


// ...
var result = request.BeginGetResponse(...)
// , BeginGetResponse doesnt timeout...
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle,...)

+2

Source: https://habr.com/ru/post/1725090/


All Articles