So i have tiny asp.net application containing the only page.
It is code from Page_Load method (it is only code in code-behind):
string url = "https://api.vkontakte.ru/oauth/access_token?client_id=123&client_secret=123&code=123&redirect_uri=mysite.com";
var webRequest = (HttpWebRequest)WebRequest.Create(url);
/*
if i comment this line
i get exception an exception with following message
The remote server returned an error: (407) Proxy Authentication Required
*/
webRequest.Proxy = null;
using (var response = (HttpWebResponse)webRequest.GetResponse()) //
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
string str = reader.ReadToEnd();
TokenBox.Text = str;
}
}
So what is my problem? This application is deployed in iis 7.5. When i ise it as iis site i get an exception WebException with message "Unable to connect to the remote server". But if i press F5 button in Visual Studio and debug my web application with IIS Express this code works fine.
What is the reason of this weird behavior? How can i fix it and make my app to work properly from IIS site?
https://blog.lextudio.com/2015/04/web-application-differences-in-visual-studio-and-iis/
To make a request out, .NET/Windows requires proper networking settings (such as proxy, authentication and so on), which might be OK for your account to run the code in VS. However, IIS obviously won't guarantee the code to work, because you did not yet set the application pool identity with the same networking settings.
Related
I have a .Net 4.5.2 WebApp that is calling my API. When I point my web app to the LocalHost version of my API, it gets the data, and comes back just fine. I published that API, and confirm that the API is working correctly with PostMan.
Then I run the exact same WebApp code, changing only the URI from localhost to live api, and I get a multiple exception error consisting of the following:
An existing connection was forcibly closed by the remote host
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
The underlying connection was closed: An unexpected error occurred on a send.
An error occurred while sending the request.
Here's my calling code
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("user", serializedUser);
response = null;
try
{
//Uri uri = new Uri("https://jsonplaceholder.typicode.com/posts/1");//https works
Uri uri = new Uri("https://api.acme.com/values/test");
//Uri uri = new Uri("http://localhost/5000/values/test"); //http localhost works
response = client.GetAsync(uri).Result;
}
catch (Exception e)
{
string er = e.Message;
}
}
EDIT 1: I created a .NET Core app from scratch, and my original code works perfectly calling my live API. My original code also work in .NET 4.5.2 calling a different "https" API.
EDIT 2:
So this is where I'm at now, I have created two generic apps from VS 2015, one is a .NET Core Web App, the other a .NET Framework Web App. I have used the above code exactly the same in both apps to call the API. In both apps, I can call a generic "https" api I found online (jsonplaceholder). I can also call the localhost version of my app at "http" from both. In the .NET Core version of the app, I can call my "https" live API and get the results I'm looking for. In the .NET Framework app I still get the same errors.
I can't figure out what the difference is between my Core and Framework requests that is getting one shut down when the other isn't.
It seems you are hosting the application on secured http environment (https). Are you using SSL certificate on the server where you are hosting your Web API? If not, It might be throwing the certificate related exceptions.
Just add the following line before the call to GetAsync and This will ignore the SSL errors.
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
This is only recommended in an intranet environment or other closed network where server identities can't be forged.
C# Ignore certificate errors?
Adding the following line before my API call fixed the issue, but I'd love to hear an explanation of what this line does, and any security risks this might impose using it in my web app.
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
Props to this answer!
IIS 8 & Windows 8
I have below sample code which I am trying to check whether a url exists, when I ran from console app it works fine, response is obtained, but when executed from server side ASP.net page it throws socket exception.
Sample code:
try
{
Uri uri = new Uri("HTTPS://test");
WebRequest http = HttpWebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse)http.GetResponse();
Stream stream = response.GetResponseStream();
}
catch (UriFormatException sds)
{
}
catch (IOException sdsd)
{
}
Error:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Any suggestions in this regard would helpful.
Without more information, my guess would be that the asp.net application is running under an account which does not have enough privs to access a network resource. You can try changing the account under which the asp.net application runs or impersonate a user with network access rights.
This is driving me crazy.
I'm trying to access a WCF service via an ASP.NET web form,
I'm setting the binding for the channelfactory up like this:
BasicHttpBinding b = null;
if (Communication.SlServiceURL.StartsWith("https"))
b = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
else
{
b = new BasicHttpBinding();
b.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
}
b.MaxBufferSize = 2147483647;
b.MaxReceivedMessageSize = 2147483647;
b.Security.Transport = new HttpTransportSecurity { ClientCredentialType = HttpClientCredentialType.Ntlm, ProxyCredentialType = HttpProxyCredentialType.None };
b.Security.Message = new BasicHttpMessageSecurity { ClientCredentialType = BasicHttpMessageCredentialType.UserName };
Then I create a new Channel Wrapper via:
public ClientChannelWrapper(Binding binding, EndpointAddress remoteAddress)
{
m_Factory = new ChannelFactory<T>(binding, remoteAddress);
}
I'm passing the binding and a https://[myservice]/myservice.svc URL as the remoteAddress.
The thing is: When I call the service in my production server with IIS 7, Windows Authentication enabled on the site and ONLY "NTLM" as the provider for the authentication, everything else disabled (no anonymous, forms, etc.)
I get the exception:
Exception type: MessageSecurityException
Exception message: The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'NTLM'.
This is pretty weird and I can't seem to find a way around this. I have also a Silverlight application hosted in another ASP.NET Form and there it works fine with this binding which is freaking me out because why wouldn't the same thing work in the ASP.NET site hosted in the same IIS site.
Also strange: When firing the site up from Visual Studio with F5 it works when accessing the production WCF service in the IIS7 machine. As soon as I deploy the site I get the exception.
Edit: It's clear now why Silverlight behaves different than ASP.NET, since Silverlight is communicating directly via the client computer with the service. Still no luck with the exception.
We have just moved to a new dedicated server that has Windows 2008 and SQL Server 2008. I am trying to access an ASP page on the same server using Server.CreateObject("MSXML2.ServerXMLHTTP").
On our previous 2003 server this worked correctly, however with the new 2008 server the operation just times out.
Here is the code:
strURL = "http://www.storeboard.com/profile/profile_view.asp?MemberID=" & MemberID & "&sid=" & cSession.SessionID
Set oXMLHttp = Server.CreateObject("MSXML2.ServerXMLHTTP")
oXMLHttp.open "GET", strURL, false
oXMLHttp.send()
IF oXMLHttp.status = 200 THEN
strOut = oXMLHttp.responseText
ELSE
strOut = "Could not get XML data."
END IF
Set oXMLHttp = nothing
The code is very simple but I get the following error:
msxml3.dll error '80072ee2'
The operation timed out
/handle404.asp, line 291
Line 291 refers to oXMLHttp.Send() line.
Is there an alternative code I can use? I use the script other places on the server that access files on other servers and they work correctly, but any access to files on our server doesn't work.
Is there an alternative method that will allow me to keep the URL intact in the browser? The person could write the URL in their browser: http://www.example.com/hello the file doesn't exist but I have a 404 handler that then points the user to the correct path without changing the browser URL which is essential for our SEO ratings.
Microsoft has a published a KB article entitled INFO: Do Not Send ServerXMLHTTP or WinHTTP Requests to the Same Server
If the ServerXMLHTTP or WinHTTP component must send a request to
another ASP on the same server, the target ASP must be located in a
different virtual directory and set to run in high isolation. Avoid
using ServerXMLHTTP or WinHTTP to send a request to an ASP that is
located in the same virtual directory.
...
A finite number of worker threads (in the Inetinfo.exe or Dllhost.exe
process) is available to execute ASP pages. If all of the ASP worker
threads send HTTP requests back to the same Inetinfo.exe or
Dllhost.exe process on the server from which the requests are sent,
the Inetinfo.exe or Dllhost.exe process may deadlock or stop
responding (hang), because the pool of worker threads to process the
incoming requests will be exhausted. This is by design.
As far as alternatives go, it depends on what you're doing with the response after you receive it. If the entire purpose of the script is to forward the request to profile_view.asp, you might be able to use Server.Transfer instead.
I had this same issue. In my case the web request I was trying to make was an internal site url (within the same app pool). With server side debugging set to enabled, the asp app pool seems to be restricted to a single worker thread. By disabling this feature, the request was then able to be processed.
msxml3.dll is pretty old. It was distributed with Internet Explorer 6 to give you a rough idea.
Can you have someone install a later version on the server?
http://support.microsoft.com/kb/269238 gives you a list of versions to send to whoever it responsible for the server.
If the problem is genuinely down to a time out you could look into switching ASP buffering off. (This based soley on a guess that if the server object started to receive a response it would hold off on the timeout front.
Alternatively you coudl try processing the value on the client side, below is a function from some code I wrote which does this....
function getDets(RateID) {
var xmlHttp;
try {
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
}
catch (e) {
try {
// Internet Explorer
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4) {
var str;
var newStr;
str=xmlHttp.responseText
newStr=str.split("|");
window.document.all.OR2.style.display="block";
window.document.all.OR3.style.display="block";
window.document.OvertimeRates.Description.value=newStr[0];
window.document.OvertimeRates.Factor.value=newStr[1];
}
}
if (RateID==0) {
window.document.OvertimeRates.Description.value="";
window.document.OvertimeRates.Factor.value="";
}
else {
xmlHttp.open("GET","GetOvertimeRate.asp?RateID="+RateID,true);
xmlHttp.send(null);
}
}
Good luck!
We have a web service running on the server. We want to use the service in local machine. Could some one kindly give all the steps to get the methods availble in the client.
We have created web methods in the server. And trying to access the same thing on the client. I can literally access those methods using the refernce variable of the server. but when I try to run it , it comes up with run time exception unable to connect to remote server.
I have added the web reference to my client class. What else I am missing. Do I need to do any kind of registration of service with client from command prompt.
I am assuming the client is unable to connect to server because the server is not running when I try to access the methods.
Any one with guidance will be helpful.
Thank you
Hari Gillala
I have added web refernce to this below client class using http://ipaddressofwerver/decisionclass/decisionclass.svc
The code:
try
{
DecisionClass ds = new DecisionClass();
string s = ds.Url;
Label1.Text = s;
string [] a = ds.GetList();
foreach (string i in a)
{
Response.Write(i);
}
}
catch (Exception Ex)
{
Response.Write(Ex.Message);
}
I am assuming the client is unable to connect to server because the server is not running when I try to access the methods.
If it's not running, it won't generate a WSDL either. However, it may have been running while you created the web reference, and then stopped.
Here are some things you can try to track down the problem:
Open the web service's URL, as specified in the web reference, in a regular web browser. This should bring up the web service's documentation page, and if you're running locally and haven't changed the web service's web.config, you can even call some simple methods using the provided test forms
See if you can access the web service with SoapUI or a similar tool.
Also, make sure you're running the web service in IIS, not in the Visual Studio development server - IIS will keep running when you close the project or even Visual Studio, but the development server might not.