HttpWebRequest Exception - asp.net

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

Related

HTTP Request with .NET Core resulting in a 403 Forbidden error

I'm trying to make a web request to a 3rd party endpoint using .NET Core 2. The endpoint requires authentication with a client certificate and a username and password. So far everything I try results in a 403 (Forbidden) error. I've tried the following so far:
try
{
var handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential(username, password);
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.SslProtocols = SslProtocols.Tls12;
handler.ClientCertificates.Add(new X509Certificate2(certificate));
var client = new HttpClient(handler);
var result = await client.GetStringAsync(url);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
I've also tried:
try
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var request = (HttpWebRequest)WebRequest.Create(url);
var cert = new X509Certificate2(certificate);
request.ClientCertificates.Add(cert);
request.Credentials = new NetworkCredential(username, password);
request.Method = "GET";
var response = (HttpWebResponse)request.GetResponse();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
So far I'm just trying to do a GET but eventually I'll need to do a POST.
As I said above, both result in a 403. If I run the second sample against the .NET Framework it works just fine. Also, if I have Fiddler running then I get an OK status returned and not a 403.
Any thoughts on what I'm doing wrong that is preventing .NET Core from successfully connecting to an endpoint?
I ended up switching the code to what I have below and that did the trick. I set the ClientCertificateOption to be Automatic and I removed manually specifying the certificate.
try
{
var handler = new HttpClientHandler();
handler.Credentials = new NetworkCredential(username, password);
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
handler.SslProtocols = SslProtocols.Tls12;
var client = new HttpClient(handler);
var result = await client.GetStringAsync(url);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}

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?

The remote server returned an error: (400) Bad Request. When try to login with facebook in asp.net

I am try to login with a user with Facebook account in my website, but the applcation gives me error that The remote server returned an error: (400) Bad Request.
Below is my code:
public string WebRequest(Method method, string url, string postData)
{
HttpWebRequest webRequest = null;
StreamWriter requestWriter = null;
string responseData = "";
webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
webRequest.Method = method.ToString();
webRequest.ServicePoint.Expect100Continue = false;
webRequest.UserAgent = "[You user agent]";
webRequest.Timeout = 50000;
if (method == Method.POST)
{
webRequest.ContentType = "application/x-www-form-urlencoded";
//POST the data.
requestWriter = new StreamWriter(webRequest.GetRequestStream());
try
{
requestWriter.Write(postData);
}
catch
{
throw;
}
finally
{
requestWriter.Close();
requestWriter = null;
}
}
responseData = WebResponseGet(webRequest);
webRequest = null;
return responseData;
}
*It gives me error in this method:*
public string WebResponseGet(HttpWebRequest webRequest)
{
StreamReader responseReader = null;
string responseData = "";
try
{
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
}
catch
{
throw;
}
finally
{
webRequest.GetResponse().GetResponseStream().Close();
responseReader.Close();
responseReader = null;
}
return responseData;
}
Ooo been a while since Iv'e played with webRequest but I think your problem might be
webRequest.GetResponse().GetResponseStream().Close();
in the finally block. Since you've already called
webRequest.GetResponse().GetResponseStream()
in the body of try block. Documentation states:
The GetResponse method sends a request to an Internet resource and
returns a WebResponse instance. If the request has already been
initiated by a call to GetRequestStream, the GetResponse method
completes the request and returns any response.
Therefore as I read it, the response had already been returned in the try block and then when you call it again in the finally block, it fails...since it's already been retrieved. Just comment out that line and see how you go. The StreamReader should close the underlying connection when you close it.
So try:
public string WebResponseGet(HttpWebRequest webRequest)
{
StreamReader responseReader = null;
string responseData = "";
try
{
responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
responseData = responseReader.ReadToEnd();
}
catch
{
throw;
}
finally
{
responseReader.Close();
}
return responseData;
}

How to release the resource of the used HttpRequest and HttpRespone

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);
}

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");
}
}
}

Resources