ASP.NET receives post data issue - c#

I used ASP.NET to write a web page that accesses other websites to log in to the API, and it was successfully placed on my server, but when it was placed on the school's server to receive the token from the post, the following error was reported:
Server Error in '/classMeeting' Application. A connection attempt failed because the connecting party did not properly reply after a period of time or the connected host became unresponsive. 112.65.235.59:443
Description: An unhandled exception occurred during the execution of the current web request.
Please review the stack trace for more information about the error and where it originated in the code.
Exception Details:
System.Net.Sockets.SocketException:
A connection attempt failed because the connected party did not properly reply after a period of time or the connected host became unresponsive. 112.65.235.59:443
Source Error:
An unhandled exception was generated during the execution of the current webrequest. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +309
System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception) +633
System.Net.HttpWebRequest.GetRequestStream(TransportContext& context) +708
System.Net.HttpWebRequest.GetRequestStream() +21
classMeeting.index.GetAccess_token(String code, String client_id, String redirect_uri, String client_secret) in C:\Users\admin\source\repos\classMeeting\index.aspx.cs:130 classMeeting.index.readyLogin() in C:\Users\admin\source\repos\classMeeting\index.aspx.cs:32
classMeeting.index.Page_Load(Object sender, EventArgs e) in C:\Users\admin\source\repos\classMeeting\index.aspx.cs:25
System.Web.UI.Control.OnLoad(EventArgs e) +109
System.Web.UI.Control.LoadRecursive() +68
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3321
My source code is:
public static string GetAccess_token(string code, string client_id, string redirect_uri, string client_secret)
{
var url = "https://openapi.yiban.cn/oauth/access_token";
byte[] byteArray = Encoding.UTF8.GetBytes(string.Format("client_id={0}&client_secret={1}&code={2}&redirect_uri={3}", client_id, client_secret, code, redirect_uri));
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
webRequest.Method = "Post";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = byteArray.Length;
ServicePointManager.DefaultConnectionLimit = 50;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
StreamReader php = new StreamReader(response.GetResponseStream(), Encoding.Default);
return php.ReadToEnd();
}
How should we do to fix this error?

If you get any error code like 10036 for a socket connection error then you can find the related error section from this link
Check the parameters you use for connection like hostname and port, and also make sure your firewall doesn't drop packages or block your connection.

The code you provided is correct, there are several reasons for this phenomenon:
Check whether the status of the server is abnormal. For example, there may be a state of not starting or being paralyzed.
Whether the status of your destination URL is normal. Whether there is an unreachable state.
Whether your server can access your target website. Due to the server's need for a secure environment, there are usually some URLs that cannot be accessed by the server. At this point you need to change your server port. If it still doesn't work, try sending and receiving web requests to hosts that it can access successfully.

Related

FTP Upload from WinService fails

I have made a small test application(WinForms C#) to test FTP upload. This works perfectly.
I try to use the exact same method in a Windows Service I'm currently working on, but there I get '(426) Connection closed; transfer aborted.'-message.
I have made sure several times that the parameters to the method are exactly the same. They are! Next thought was the account my service is running under, but I've tried all possibilities, even running the service as 'User', supplying my own credentials. Then it should act like the WinForms app, right? No, it doesn't!
It's running fine until the line using (var requestStream = request.GetRequestStream()) which is the point of failure.
The FTP-server in question only allows active connections, so request.UsePassive is set to false.
Anyone got a clue?
public void UploadToFtp(string url, string filePath, string username, string password, bool mode)
{
var fileName = Path.GetFileName(filePath);
var request = (FtpWebRequest)WebRequest.Create(url + fileName);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = !mode;
request.UseBinary = true;
request.KeepAlive = false;
using (var fileStream = File.OpenRead(filePath))
{
using (var requestStream = request.GetRequestStream())
{
fileStream.CopyTo(requestStream);
requestStream.Close();
}
}
var response = (FtpWebResponse)request.GetResponse();
response.Close();
}
Adding trace logs of both scenarios:
Using a Windows application:
WebRequest::Create(ftp://someurl/somefile.txt)
FtpWebRequest#63289421::.ctor(ftp://someurl/somefile.txt)
Exiting WebRequest::Create() -> FtpWebRequest#63289421
Current OS installation type is 'Client'.
RAS supported: True
ServicePoint#14173886::ServicePoint(someurl:21)
FtpWebRequest#63289421::GetRequestStream()
FtpWebRequest#63289421::GetRequestStream(Method=STOR.)
FtpControlStream#22525719 - Created connection from 10.10.10.103:1865 to nnn.nnn.nnn.nnn:21.
Associating FtpWebRequest#63289421 with FtpControlStream#22525719
FtpControlStream#22525719 - Received response [xxxx
someurl>PROD server
Port21>Use active mode>
xxxx]
Sending command [USER myusername]
Received response [331 Enter password]
Sending command [PASS ********]
Received response [230-User logged in
Hi,I'am datagear PROD.
230 User logged in]
Sending command [OPTS utf8 on]
Received response [200 Command OPTS succeed]
Sending command [PWD]
Received response [257 "/CitData" is current directory]
Sending command [TYPE I]
Received response [200 Transfer mode set to BINARY]
Sending command [PORT 10,10,10,103,7,74]
Received response [200 Command PORT succeed]
Sending command [STOR somefile.txt]
Received response [150 Uploading in BINARY file somefile.txt]
Exiting FtpWebRequest#63289421::GetRequestStream()
Received response [226 Transfer completed]
Sending command [QUIT]
Received response [221-bye
Bye-Bye,see you again.
Using a Windows Service:
WebRequest::Create(ftp://someurl/somefile.txt)
FtpWebRequest#63289421::.ctor(ftp://someurl/somefile.txt)
Exiting WebRequest::Create() -> FtpWebRequest#25425822
Current OS installation type is 'Client'.
ServicePoint#31665793::ServicePoint(someurl:21)
FtpWebRequest#25425822::GetRequestStream()
FtpWebRequest#25425822::GetRequestStream(Method=STOR.)
FtpControlStream#51484875 - Created connection from 10.10.10.103:1759 to nnn.nnn.nnn.nnn:21.
Associating FtpWebRequest#25425822 with FtpControlStream#51484875
FtpControlStream#51484875 - Received response [xxxx
someurl>PROD server
Port21>Use active mode>
xxxx]
Sending command [USER myusername]
Received response [331 Enter password]
Sending command [PASS ********]
Received response [230-User logged in
Hi,I'am datagear PROD.
230 User logged in]
Sending command [OPTS utf8 on]
Received response [200 Command OPTS succeed]
Sending command [PWD]
Received response [257 "/CitData" is current directory]
Sending command [TYPE I]
Received response [200 Transfer mode set to BINARY]
Sending command [PORT 10,10,10,103,6,224]
Received response [200 Command PORT succeed]
Sending command [STOR somefile.txt]
Received response [426 Transfer failed]
(Releasing FTP connection#51484875.)
GetRequestStream - The remote server returned an error: (426) Connection closed; transfer aborted..
at System.Net.FtpWebRequest.SyncRequestCallback(Object obj)
at System.Net.CommandStream.Dispose(Boolean disposing)
at System.IO.Stream.Close()
at System.Net.ConnectionPool.Destroy(PooledStream pooledStream)
at System.Net.ConnectionPool.PutConnection(PooledStream pooledStream, Object owningObject, Int32 creationTimeout, Boolean canReuse)
at System.Net.FtpWebRequest.FinishRequestStage(RequestStage stage)
at System.Net.FtpWebRequest.GetRequestStream()
Exiting FtpWebRequest#25425822::GetRequestStream()
The one that works has a line saying 'RAS Supported'. Maybe interesting, don't know.
The Windows Firewall caused the problem. When running from a WinService I had to open the firewall for this service. When running from VS environment it seems that the firewall is already open for VS (although the list of pass-through applications in WinFirewall don't show it) and therefore all seems to run well.

Windows Phone Web Exception 404 not found but server gets requests

As the title says I am trying to run a Windows Phone App which is supposed to communicate with a Restful API(running on localhost). My server is actually getting my Http requests but Visual Studio keeps throwing this error:
"The remote server returned an error: NotFound."
private void connect_tap(object sender, System.Windows.Input.GestureEventArgs e)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.BeginGetResponse(GetResponseCallback, request);
}
void GetResponseCallback(IAsyncResult result)
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;
if (request != null)
{
WebResponse response = request.EndGetResponse(result);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string read = streamRead.ReadToEnd();
Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(read);
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
});
streamResponse.Close();
streamRead.Close();
response.Close();
}
}
This is the full error:
{System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound.
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClasse.b__d(Object sendState)
at System.Net.Browser.AsyncHelper.<>c__DisplayClass1.b__0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at IonisSphere.Connect.GetResponseCallback(IAsyncResult result)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClass1d.b__1b(Object state2)}
The Web Exception occurs at the EndGetResponse() call. I removed the try/catch around to see the error but when it's there it always goes in the catch section and nothing happens.
I don't understand what is it not finding since my server gets my requests ...
It works fine with Postman by the way. I also tried with a POST method but got exactly the same result.
I'm stuck with this since a few days and I couldn't find anyhing helpful on the internet. I am quite new on Windows Phone and I know this is propably a stupid mistake but thanks in advance for the ones who will try to teach me =)

Strange object disposed exception on HttpWebResponse

I am working on a program that automatically queries a website every 5 seconds. It has been working fine for the last few days, but today when I simply restarted it, it keeps throwing System.ObjectDisposedException on the line marked underneath. I should mention that accessing this URL via a browser on the same machine works fine.
Code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.bitstamp.net/api/ticker/");
request.Method = "GET";
try
{
// ObjectDisposedException thrown here
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
string resultString = reader.ReadToEnd();
return resultString;
}
}
}
catch (WebException ex)
{
// Handle it
}
Stack Trace:
System.ObjectDisposedException occurred
_HResult=-2146232798
_message=Cannot access a disposed object.
HResult=-2146232798
IsTransient=false
Message=Cannot access a disposed object.
Object name: 'SslStream'.
Source=System
ObjectName=SslStream
StackTrace:
at System.Net.Security.SslState.ValidateCreateContext(Boolean isServer, String targetHost, SslProtocols enabledSslProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, Boolean remoteCertRequired, Boolean checkCertRevocationStatus, Boolean checkCertName)
InnerException:
Is there something I am doing wrong? I do not even access the response stream before the using, how can it be disposed?
EDIT: Added url and stack trace
Simplifying things a bit and just doing a:
WebRequest.Create("https://www.bitstamp.net/api/ticker/").GetResponse();
I'm getting WebException "The server committed a protocol violation. Section=ResponseHeader Detail=CR must be followed by LF", which apparently is indicative of a problem at the server end, and one (perhaps the only) way round it is to add the following to your config file:
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true" />
</settings>
</system.net>
Worked for me anyway.

Windows Phone - failing to get a string from a website with login information

I am new to accessing web services with Windows Phone 7/8. I'm using a WebClient to get a string from a php-website. The site returns a JSON string but at the moment I'm just trying to put it into a TextBox as a normal string just to test if the connection works.
The php-page requires an authentication and I think that's where my code is failing. Here's my code:
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("myUsername", "myPassword");
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri("https://www.mywebsite.com/ba/php/jsonstuff.php"));
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
string data = e.Result;
this.jsonText.Text = data;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
This returns first a WebException and then a TargetInvocationException. If I replace the Uri with for example "http://www.google.com/index.html" the jsonText TextBox gets filled with html text from Google (oddly enough, this also works even when the WebClient credentials are still set).
So is the problem in the setting of the credentials? I couldn't find any good results when searching for guides on how to access php-pages with credentials, only without them. Then I found a short mention somewhere to use the WebClient.Credentials property. But should it work some other way?
Update: here's what I can get out of the WebException (sorry for the bad formatting):
System.Net.WebException: The remote server returned an error: NotFound. --->System.Net.WebException: The remote server returned an error: NotFound.
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.ClientHttpWebRequest.<>c_DisplayClasse.b_d(Object sendState)
at System.Net.Browser.AsyncHelper.<>c_DisplayClass1.b_0(Object sendState)
--- End of inner exception stack trace ---
at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state)
at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)
Update 2: Here's the error log line:
Nov 16 17:51:12 myservice httpd[21036]: 127.0.0.1 - - [16/Nov/2012:17:51:12 +0200] "GET /ba/php/jsonstuff.php?origpath=/ba/php/jsonstuff.php HTTP/1.1" 401 290 "-" "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"
401 I guess would suggest false credentials?
In my opininion you really need to see how the server handles your request. "NotFound" in WebException could mean that you're referring to a location that doesn't exist. But I'm sure that you pass the right URL. So there must be some logic on the server that redirects you.
If you go to the url using your desktop browser - do you have any kind of SSL certificate error or warning? Maybe that's the reason. Try navigating on your phone using IE.
Or you could set up another host just to give it a try.
I'll set up a host on my machine and try it.
The problem is with the SSL certificate I guess. WP is very strict when it goes to checking SSL certificates, so you should try without ssl or install cert on your emulator/phone or install valid (not self generated) cert on your server.
Okay, so I found a way to get this working. The problem was that the WebClient class couldn't properly handle the cookies of the web service.
After some Google searches I found this solution and it works perfectly:
http://firebelly.net/post/3341374382/cookie-aware-webclient-for-wp7
So basically you just make your own client class that extends the WebClient class which can store cookies.

How to AutoDetect/Use IE proxy settings in .net HttpWebRequest

Is it possible to detect/reuse those settings ?
How ?
The exception i'm getting is
This is the exception while connecting to http://www.google.com
System.Net.WebException: Unable to connect to the remote server --->
System.Net.Sockets.SocketException: 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 66.102.1.99:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot,
SocketAddress socketAddress)
at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure,
Socket s4, Socket s6, Socket& socket, IPAddress& address,
ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout,
Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.GetResponse()
at mvcTest.MvcApplication.Application_Start() in
C:\\home\\test\\Application1\\Application1\\Program.cs:line 33"
HttpWebRequest will actually use the IE proxy settings by default.
If you don't want to use them, you have to specifically override the .Proxy proprty to either null (no proxy), or the proxy settings of you choice.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://news.bbc.co.uk");
//request.Proxy = null; // uncomment this to bypass the default (IE) proxy settings
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Console.WriteLine("Done - press return");
Console.ReadLine();
I was getting a very similar situation where the HttpWebRequest wasn't picking up the correct proxy details by default and setting the UseDefaultCredentials didn't work either. Forcing the settings in code however worked a treat:
IWebProxy proxy = myWebRequest.Proxy;
if (proxy != null) {
string proxyuri = proxy.GetProxy(myWebRequest.RequestUri).ToString();
myWebRequest.UseDefaultCredentials = true;
myWebRequest.Proxy = new WebProxy(proxyuri, false);
myWebRequest.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
}
and because this uses the default credentials it should not ask the user for their details.
Note that this is a duplicate of my answer posted here for a very similar problem: Proxy Basic Authentication in C#: HTTP 407 error
For people having problems with getting this to play nice with ISA server, you might try to set up proxy in the following manner:
IWebProxy webProxy = WebRequest.DefaultWebProxy;
webProxy.Credentials = CredentialCache.DefaultNetworkCredentials;
myRequest.Proxy = webProxy;
This happens by default, if WebRequest.Proxy is not set explicitly (by default it's set to WebRequest.DefaultWebProxy).

Categories