How to release the resource of the used HttpRequest and HttpRespone - asp.net

All, Usually if we want to release the resource of something like Connection or Stream. we have to call the method like close() to make that in Asp.net.
But I don't find any method of HttpWebRequest like close() to let Asp.Net to release the resource.
So, Commonly if I want to use HttpWebRequest or HttpWebResponse , the code snippet kind like this way . Please review below. Is there anything wrong with it ? I am not sure about that . Thanks.
try
{
HttpWebRequest request = createGetHttpRequest(detailModel, RequestServiceType.GetToken,null);
string returnedContent = string.Empty;
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
returnedContent = reader.ReadToEnd();
reader.Close();
}
}
// string statusCode = response.StatusCode.ToString();
response.Close();
}
}
catch (Exception e)
{
Log.Write(e);
}

Related

Created a Soap Webservice and calling it in asp.net uisng code and getting error of The remote name could not be resolved

I had developed one web service in SOAP format and trying to access service in asp.net using the below mentioned code.
public static void CallWebService()
{
try
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var _url = "https://test.in/ModelDetail/Service.asmx";
var _action = "https://test.in/ModelDetail/GetWarrantyDetails";
XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
//using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
using (HttpWebResponse webResponse= (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.Write(soapResult);
}
}
catch(Exception ex) { throw ex; }
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(#"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:tem='https://ndb.bmw.in/'><soapenv:Header/><soapenv:Body><tem:GetWarrantyDetails><tem:IP><demono>WBA3Y37070D45</demono></tem:IP></tem:GetWarrantyDetails></soapenv:Body></soapenv:Envelope>");
return soapEnvelop;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
but when i call this code i get error of The remote name could not be resolved.
Tried all method but get this error only.
What is missing or wrong i am doing?

HttpWebRequest Exception

I try to do httprequest with asp.net and C#. And I get an exception with message "The Web server refused the connection. The Web server refused the connection"
This is my code:
var webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Proxy = proxy; // Proxy's credentials have login and password
try
{
using (var response = (HttpWebResponse) webRequest.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.ProtocolError)
{
WebResponse resp = e.Response;
using (var sr = new StreamReader(resp.GetResponseStream()))
{
string str = sr.ReadToEnd();
}
}
return null;
}
And in method webRequest.GetResponse() I get WebException that I read in catch block. str variable contains html-code that looks like this:
http://i.stack.imgur.com/3QIn3.png
Unfortunatelly I can not post images.
How can I fix this error?
P.S. If it is important I use Forefront TMG but I dont know whether it can affect

HttpWebRequest getting time out issue

I have a function UpdateCRM() which will make http web request to my CRM server to update data.
If it calling once it working fine. But when we calling UpdateCRM() inside a loop, it is getting time out after updating some record.
Is there any better to solve the problem.
Here is my UpdateCRM() method.
function UpdateCRM()
{
HttpWebRequest httpWebRequest = null;
//Convert object to JSON
sJSON = oSerializer.Serialize(emailSendoutList);
httpWebRequest = (HttpWebRequest)WebRequest.Create(ConfigUtility.crmUpdateServiceURL + "/UpdateCrmAfterEMailed");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
httpWebRequest.Timeout = 600000;
httpWebRequest.ReadWriteTimeout = 600000;
httpWebRequest.ContentLength = sJSON.Length;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(sJSON);
streamWriter.Flush();
streamWriter.Close();
}
}
You need to close to object after using it.
try adding this after using streamwriter.
httpWebRequest.abort();
EDIT:
Try like this, maybe it response is causing the problem?
HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();
using (var streamWriter = new StreamWriter(Response.GetRequestStream()))
{
streamWriter.Write(sJSON);
streamWriter.Flush();
streamWriter.Close();
}
Response.Close();

Error :The remote server returned an error: (401) Unauthorized

I want get picture of internet and insert into word .
I use this code .
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
System.Net.WebRequest request =
System.Net.HttpWebRequest.Create("http://spsdev2:1009");
System.Net.WebResponse response = request.GetResponse();
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
//Send an HTTP request and get the image at the URL as an HTTP response
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(fileName);
WebResponse myResp = myReq.GetResponse();
//Get a stream from the webresponse
Stream stream = myResp.GetResponseStream();
I get error in myReq.GetResponse();
Error :The remote server returned an error: (401) Unauthorized.
Edit
This code work for me :)
myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;
I add credentials for HttpWebRequest.
myReq.UseDefaultCredentials = true;
myReq.PreAuthenticate = true;
myReq.Credentials = CredentialCache.DefaultCredentials;
Shouldn't you be providing the credentials for your site, instead of passing the DefaultCredentials?
Something like request.Credentials = new NetworkCredential("UserName", "PassWord");
Also, remove request.UseDefaultCredentials = true; request.PreAuthenticate = true;
The answers did help, but I think a full implementation of this will help a lot of people.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace Dom
{
class Dom
{
public static string make_Sting_From_Dom(string reportname)
{
try
{
WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultCredentials;
// Retrieve resource as a stream
Stream data = client.OpenRead(new Uri(reportname.Trim()));
// Retrieve the text
StreamReader reader = new StreamReader(data);
string htmlContent = reader.ReadToEnd();
string mtch = "TILDE";
bool b = htmlContent.Contains(mtch);
if (b)
{
int index = htmlContent.IndexOf(mtch);
if (index >= 0)
Console.WriteLine("'{0} begins at character position {1}",
mtch, index + 1);
}
// Cleanup
data.Close();
reader.Close();
return htmlContent;
}
catch (Exception)
{
throw;
}
}
static void Main(string[] args)
{
make_Sting_From_Dom("https://www.w3.org/TR/PNG/iso_8859-1.txt");
}
}
}

Handle json error message from REST API through HTTPWebRepsonse

I am consuming REST API (provided by client) in C#/asp.net and manipulate json result returned by that REST API. i have consume it by following code.
HttpWebResponse res = null;
string ReturnBody = string.Empty;
string requestBody = string.Empty;
WebRequest request = WebRequest.Create(Path);
request.ContentType = "application/json";
request.Method = "POST";
request.ContentLength = json.Length;
//Add Basic Auhtentication header
string authInfo = Username + ":" + Password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
System.IO.StreamWriter sw = new System.IO.StreamWriter(request.GetRequestStream());
sw.Write(json);
sw.Close();
res = (HttpWebResponse)request.GetResponse();
if (res != null)
{
using (StreamReader sr = new StreamReader(res.GetResponseStream(), true))
{
ReturnBody = sr.ReadToEnd();
StringBuilder s = new StringBuilder();
s.Append(ReturnBody);
sr.Close();
}
}
I have put above code in try catch block, so it works properly if it will return success code(200) so i can consume json response from res object as per above code
but when that REST API gives error then it will redirect to catch and res will be null so i can not access json response of error message as i can get it by Fiddler as per shown in below fig.
so help me about How can i consume that json error response through my code?
Thanks in Advance! for any help.
You will be probably getting WebException - inspect the status property. In your case, it will indicate protocol error i.e. 401/403 etc. In such case Response property can be use to get actual HTTP response. For example,
try
{
res = (HttpWebResponse)request.GetResponse();
// handle successful response
...
}
catch(WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
var response = (HttpWebResponse)ex.Response;
// use the response as needed - in your case response.StatusCode would be 403
// and body will have JSON describing the error.
..
}
else
{
// handle other errors, perhaps re-throw
throw;
}
}

Resources