show webservice soapexception response in the client in ASP.NET - asp.net

I am trying to make a Test Webservice and throw a SoapException. But when I open the service through browser, it shows Internal server error - 500.
If i try to consume it manually by sending a manually created SoapRequest (in stringbuilder), I get the same error "Servererror - 500" in Visual Studio itself in the line "WebResponse response = req.GetResponse()"
Is there anyway I can actually see the "fault in response XML".

It sounds like there is something wrong with the service and you need to debug it on the server side rather than the client side. I come to this conclusion because you have a problem with your client code and a web browser.
Assuming you are using .NET have you enabled display of ASP.NET errors on the server? See this article for info.
Update:
So you are throwing an error on the server and want to get the error text on the client? An error on the server is supposed to result in a 500 error message and is unlikely to return any XML to the client. Perhaps you can pass something to the SoapException constructor?
Have you looked at the docs for SoapException? They have some examples of passing information using the Detail property of SoapException.

Can you get to the asmx (assuming you are using asmx) in the browser to see if it is working at all?

after surfing through for 5-6 hours finally got it......here it is:
When you are getting the response manually, use the following:
try
{
WebResponse response = req.GetResponse();
Stream str = response.GetResponseStream();
StreamReader rdr = new StreamReader(str);
Response.Write(rdr.ReadToEnd());
Response.End();
}
catch (WebException webEx)
{
Stream str = webEx.Response.GetResponseStream();
StreamReader rdr = new StreamReader(str);
Response.Write(rdr.ReadToEnd());
Response.End();
}

Related

HttpClient on ASP.NET Core application times out when connecting to service on localhost

I have a XML-RPC server (using XML-RPC.net) running as a .NET console application. I'm trying to connect to it via my ASP.NET Core (2.1.1) web app but the client keeps timing out. Postman also returns a response immediately without issues.
Here is how I'm calling it:
HttpClient client = _clientFactory.CreateClient();
client.Timeout = TimeSpan.FromSeconds(10);
var httpRequest = new HttpRequestMessage(HttpMethod.Post, instance.ServiceUrl);
var stringContent = new ByteArrayContent(Encoding.UTF8.GetBytes(request.ToString()));
httpRequest.Content = stringContent;
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("text/xml");
var httpResponse = await client.SendAsync(httpRequest);
var response = await httpResponse.Content.ReadAsByteArrayAsync();
I can see that the request was made successfully as the console app returns a response. Fiddler shows there was a 200 response but await client.SendAsync(httpRequest); times-out!
The request usually completes in under 10ms so the timeout value is just for debugging, if I leave it out it would take 60s. The response returns XML.
I've tried rewriting this to use StringContent and using PostAsync, same issue. I also attempted to rewrite this using WebClient but it returned The remote server returned an error: (100) Continue. not sure if that's relevant.
Been stuck on this for a whie, anyone know what could be happening?
OK I did some googling and it looks like I needed this line:
client.DefaultRequestHeaders.ExpectContinue = true;
It was definitely related to 100 status code returned not being handled properly.
Found it here:
https://social.msdn.microsoft.com/Forums/en-US/042016f0-d70e-42f9-9924-5febeb2bea86/excluding-the-quotexpect-100continuequot-header-from-httpwebrequest-posts?forum=winappswithcsharp

Why is Web Request content truncated

I have a Web Service which is doing some screen scraping of an aspx website.
I can get it to log in successfully, but then when I submit a request, it returns a server error. When I check it out with Fiddler, it shows that the content (the query string) is being truncated so it is not all submitted. The content is quite long over 3600 chars. (Not my choice, it's just the way the website was created and what it expects.)
HttpWebRequest webRequest = WebRequest.Create(REQUESTUSAGE) as HttpWebRequest;
webRequest.CookieContainer = this.Cookies;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
requestWriter.Write(GetPostDataForRequest());
WebResponse response = null;
try
{
response = webRequest.GetResponse();
}
catch (Exception ex)
{}
The GetPostDataForRequest returns the content, but like I said, Fiddler shows it is missing the last 600 chars or so for no apparent reason. The debugger shows the string is returned as expected, but somehow it does not get written correctly.
So how to I get it to submit the full string?
OK, I got this resolved. I was not closing the requestWriter.
There are usually limits to the request size - take a look at maximum length of HTTP GET request?
It appears that you are running into a browser issue, not a server issue. Can you issue the request with a command line tool (i.e. something like wget) to verify that it is not a problem with the server?
You can also try a different browser, which may have different limits.

How to capture IIS 500 server error detail when received in a WebException?

I have code that uses an HttpWebRequest to request a .ASP page (asp 3.0), with some parameters in the URL. That ASP page will generate a PDF by getting some data from a database. Due to error in the ASP code, I'm getting a WebException with IIS's 500 server error when I try to get the response from the request. And that's fine, but the exception's message doesn't really say anything other than 500 error occurred.
If I copy paste the URL that I'm requesting in IE, I do get some details since I have friendly errors disable and IIS configured to send the real error text to the user.
"Technical Information (for support personnel)
Error Type:
ADODB.Recordset (0x800A0CC1)
Item cannot be found in the collection corresponding to the requested name or ordinal.
"
I've done a QuickWatch on the Exception and visited all of the properties, but not one contained this data.
Is there a way to get this information on the WebException?
Thanks.
Is there a way to get this information on the WebException?
Yes, you can read the response body:
try
{
...
}
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
string text = reader.ReadToEnd();
// text will contain the response from the server
}
}

ASP.NET Facebook graph api

PROBLEM:2nd call to the graph api fails every time with Bad Request 400 error
If I do the following things, I can never get past #4.
Authenticate with facebook to get authtoken. It redirects back to the page with code querystring param
I get the authtoken from param and make a call to the following url
string url = "https://graph.facebook.com/me?access_token=" + Token; (any graph api call works fine on the first call)
I get json data back. No problem. Now I have the id info from facebook.
I try to repeat the process. Every call to https://graph.facebook.com/me/xxxxxx fails. If I try getting a new token or using the initial token I get Bad Request 400 error.
There must be an order of operations that needs to occur (requests and getting tokens) that I don't understand.
(IT IS NOT AN apikey or apisecret PROBLEM)
What you describe should work. Be sure that when you get the 400-Bad Request error that you catch the WebException and read the content of the Response. It should provide you with the reason the API call failed. The catch portion of your try/catch block would look something like this:
catch (WebException ex)
{
using (StreamReader reader = new StreamReader(ex.Response.GetResponseStream()))
{
string jsonMessageString = reader.ReadToEnd();
}
}
Try this API, it's new and supported. (ie. I support it) See if it's authentication resolves your issue. If you're like me then this would have saved you hours of time fiddling with it. Well worth the 50 bucks.

Silverlight's WebClient isn't connecting to my server

I've got a problem here.
I've got an ASP.net website hosting a silverlight 2 application.
I'd like the site to communicate to and fro from the silverlight app, and I'm doing this via http requests. Incidentally, if anyone knows a better way, please do tell me.
My server's got the following http listener set up. I copied this from a tutorial site somewhere, since it's mainly experimentation at the moment :
HttpListener listener = new HttpListener ( );
listener.Prefixes.Add("http://localhost:4531/MyApp/");
listener.Start( );
// Wait for a client request:
HttpListenerContext context = listener.GetContext( );
// Respond to the request:
string msg = "You asked for: " + context.Request.RawUrl;
context.Response.ContentLength64 = Encoding.UTF8.GetByteCount (msg);
context.Response.StatusCode = (int) HttpStatusCode.OK;
using (Stream s = context.Response.OutputStream)
using (StreamWriter writer = new StreamWriter (s))
writer.Write (msg);
listener.Stop( );
I'm using the following code to send a request :
private void MyButton_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
b.Content = "Hello World";
Uri serviceUri = new Uri("http://localhost:4531/MyApp/");
WebClient downloader = new WebClient();
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(TestDownloadStoriesCompleted);
downloader.DownloadStringAsync(serviceUri);
}
void TestDownloadStoriesCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
TextBox1.Text = e.Result;
}
}
My problem is that I can connect to the webserver from a console application using pretty much the same code (I tested it by setting a breakpoint in the code), however nothing happens when I click the button in silverlight. (I've added the "Hello World" to test that I am indeed connecting the delegate to the button.)
I've read that silverlight needs policies to connect via webclient, but it shouldn't be the case if I'm using the same server and the same domain for both the server and the silverlight application!
Thanks for all your replies!
EDIT : I am recieving this exception :
System.Security.SecurityException ---> System.Security.SecurityException: Security error.
Also, based on what I'm reading apparently to be site-of-origin, the deployment URI of the xap and the request URI must also be of the same port.
However, when I set the properties for the server to be hosted on a specific port, and I set the listener to listen to that same port, it fails with the message that The process cannot access the file because it is being used by another process. I assume it is because the http listener can't listen to the same port being used to host it :|
But then how can I make Silverlight perform host of origin webclient requests?
Since this is only a test add an "else TextBox1.Text=e.Error.ToString();" in your TestDownloadStoriesCompleted handler to see what error you get.
EDIT:
You can't host both the asp.net app and your listener on the same port - you could fix this by using a different port and serving a clientaccesspolicy.xml from your httplistener.
However I think it would make more sense for you to take a look at WCF web services (you add the svc to your asp.net app). Here's a sample.
you can use tools like http://www.fiddler2.com/fiddler2/
to actually see what is going on during the request....
This can give some help for further debugging...
I am now using HTTP handlers for communication. It seems that they will work fine enough for my purpose, although I still want to try out some WCF.

Resources