Fiddler exception different than C# exception - c#

We contact an Azure webservice to send over certain information.
When I send the request from C#, the exception provides the stacktrace from the sending side.
When I send the request from Fiddler, the exception provides the stacktrace from the receiving side.
I want to get the receiving side stacktrace in the logging as it's more usefull. Any ideas on how to do this? To my knowledge Fiddler uses HttpRequest as does C#
Code in C#:
HttpWebRequest r = (HttpWebRequest)WebRequest.Create(Adrewss);
...
HttpWebResponse response = (HttpWebResponse)r.GetResponse();
catch (Exception ex)
{
logEntry.Details = ex.ToString();
Let me know if more info is needed!
So C# ex =
500) Internal Server Error.
at System.Net.HttpWebRequest.GetResponse()
Fiddler ex:
{"Post":"System.NullReferenceException: Object reference not set to an instance of an object.\r\n at Test.Gateway.Models.Process.Transformer.GetTypeCode(String Type)\r\n etc

Fiddler doesn't use HTTPWebRequest at all, it talks to a raw socket. I'm guessing you're showing the raw text from the Response's body in Fiddler, while you're relying upon the exception (rather than the response body text) in your .NET code.

Related

Catch Soap response message c# .net

I have a Service Reference to communicate with WCF.
Now I can send the message with a method to the server. *
But I can't catch the response message. The request is fine, because I can handle the message with Fiddler Classic, but i need to handle it with c#.
Here is my code:
ServiceReference1.PUPHAXWSPortTypeClient client = new ServiceReference1.PUPHAXWSPortTypeClient();
client.ClientCredentials.HttpDigest.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
client.ClientCredentials.HttpDigest.ClientCredential.UserName = "PUPHAX";
client.ClientCredentials.HttpDigest.ClientCredential.Password = "puphax";
await client.TABATCAsync("<ATC>N05BA%</ATC>"); //* this method
If i want to storage the data to a variable or ServiceReference1.TABATCResponse tABATCRequest i got an exception which is invalid UTF-8 bytes.
Sorry for my english, here is the service reference: http://neak.gov.hu//data/cms1030808/PUPHAXWS_v1.22.wsdl

Windows Live OAuth Response Content Type Issue

I'm facing an issue with my (Register with Windows Live Account) feature in my portal
Simply the feature was suddenly stopped without any known reason and throws the following exception
Exception Message: Unexpected response Content-Type text/html
Source:
DotNetOpenAuth.Core
Stack Trace:
at DotNetOpenAuth.Messaging.ErrorUtilities.VerifyProtocol(Boolean condition, String unformattedMessage, Object[] args)
at DotNetOpenAuth.Messaging.ErrorUtilities.ThrowProtocol(String unformattedMessage, Object[] args)
at DotNetOpenAuth.OAuth2.ChannelElements.OAuth2ClientChannel.ReadFromResponseCore(IncomingWebResponse response)
at DotNetOpenAuth.Messaging.Channel.RequestCore(IDirectedProtocolMessage request)
at DotNetOpenAuth.Messaging.Channel.Request(IDirectedProtocolMessage requestMessage)
at DotNetOpenAuth.OAuth2.ClientBase.UpdateAuthorizationWithResponse(IAuthorizationState authorizationState, EndUserAuthorizationSuccessAuthCodeResponse authorizationSuccess)
at DotNetOpenAuth.OAuth2.WebServerClient.ProcessUserAuthorization(HttpRequestBase request)
at Ta3malWebParts.Membership.Registration.Registration.HandleWindowsLiveAuthorization()
The method causes this error is (WebServerClient.PrepareRequestUserAuthorization) this method should receive a JSON response from Windows Live, when i used Fiddler to check the response i found that the response content is JSON but the response header states that the response type is HTML, the above method contains an internal function validates if the returned response type is JSON or not, this validation throws the above exception.
Does any one have any idea how can we solve this issue.
Thanks in advance.

Getting headers from WebRequest

Technically I'm asking a question for a friend who writes VB, but I post as C# since more people are on it. And I personally know neither.
I'm helping him connecting to a Mobile Backend as a Service, although the way he set up he is connecting it on behalf of someone loading his own web page with ASP.net (I think).
I'm connecting to the service just fine using Python. But he is getting a 422 server response. I would like to compare the request header & content difference between his and mine.
According to Chris Doggett's post on this page down below, you can't get the headers until the request is actually sent. However, as soon as request.GetResponse() is called, Visual Studio (or the Express, not sure) seems to just halt on a break point there and say there is a 422 error and some error message on the browser. So, he can't get to the next line where he wish to print out the headers.
Two questions:
Is that some sort of debugging turned on? I thought a 422 response is a response nevertheless and the program shouldn't just stop there.
How do I print out the the content as well, not just the headers? Preferably, I want to print out the entire request in text. There is this stuff sent in JSON and I don't think that belongs to the headers but I'm not so sure.
The Create method will return an HttpWebRequest for an http/https url. The 422 status code indicates that you are somehow sending incorrect formed data to the server. GetResponse() will throw a WebException because you don't receive the
status code 200.
To get the actual headers of the response you need to handle the exception
private static void Main(string[] args)
{
WebRequest request = WebRequest.Create("http://google.com/12345"); //generate 404
try
{
WebResponse response = request.GetResponse();
}
catch(WebException ex)
{
HttpWebResponse errorResponse = ex.Response as HttpWebResponse;
if (errorResponse == null)
throw; //errorResponse not of type HttpWebResponse
string responseContent = "";
using(StreamReader r = new StreamReader(errorResponse.GetResponseStream()))
{
responseContent = r.ReadToEnd();
}
Console.WriteLine("The server at {0} returned {1}", errorResponse.ResponseUri, errorResponse.StatusCode);
Console.WriteLine("With headers:");
foreach(string key in errorResponse.Headers.AllKeys)
{
Console.WriteLine("\t{0}:{1}", key, errorResponse.Headers[key]);
}
Console.WriteLine(responseContent);
}
Console.ReadLine();
}

HttpRequest (PHP to C#) - deserialize a string

I am trying to send a string to a C# app via php, here is my code:
PHP
//set up variables
$theData = 'test
to see if a string can be deserialized';
$url = 'http://localhost:5900/';
//create the httprequest object
$httpRequest_OBJ = new httpRequest($url, HTTP_METH_POST, $options);
//add the raw post data
$httpRequest_OBJ->setRawPostData ($theData);
//send the http request
$result = $httpRequest_OBJ->send();
//get the object
$response = $result->getBody();
C#
Here is where it fails:
var methodRequestSerializer = new XmlSerializer(typeof(MethodRequest));
var methodRequest = methodRequestSerializer.Deserialize(reader) as MethodRequest;
PHP throws back the following error:
Fatal error: Uncaught exception 'HttpInvalidParamException' with message 'Empty or too short HTTP message: ''' in C:\xampp\htdocs\httpreq.php:39 inner exception 'HttpRequestException' with message 'server returned nothing (no headers, no data); Empty reply from server (http://localhost:5900/)' in C:\xampp\htdocs\httpreq.php:29 Stack trace: #0 C:\xampp\htdocs\httpreq.php(39): HttpRequest->send() #1 {main} thrown in C:\xampp\htdocs\httpreq.php on line 39
thanks.
When you say your reader comes from new StreamReader(context.Request.InputStream), I'm assuming that context is the ASP.NET HttpContext object, and your C# code is somehow deployed so as to receive an HttpRequest.
If so, the stream will contain just the bytes from the body of your HTTP request, which in the case of your example will just be the string "test to see if a string can be deserialized". Since this is not valid XML you should expect the Deserialize method call to fail.
You haven't told us what MethodRequest is, nor what an instance would look like when XML serialized. If the string you sent in the HTTP POST request were a valid XML-serialized instance of MethodRequest, I would expect your C# Deserialize method call to succeed.
If you'd be a little less coy and share fuller details of what you're trying to do and how, we might be able to help more easily.

C# HttpWebRequest.GetResponse - how is StatusCode usage handled for a non-exception vs webexception response?

Can someone help clear up the usage of the "StatusCode" property in HttpWebResponse and WebException?
For example it seems that if:
a) there is no exception, then the HttpWebResponse will have a StatusCode that could have some values that indicate both:
- success (e.g. OK, Accepted etc)
- failure (e.g. UseProxy, RequestTimeout etc)
b) there is a WebExeption throw, which itself has a response object that again has a StatusCode (which I assume is based on the same HttpStatusCode Enumeration.
Question 1
- Is there any consistency in terms of what StatusCode's will trigger a WebException (and you'd pick up the detail within the exception), versus which would come back without an exception but you'd find out the result in the StatusCode of the response object?
Question 2 - Or more specifically what is the pseduo code (or C# code itself) for trying to handle a httpWebRequest.GetResponse call such that you want to differentiate between the categories of responses for the user:
proxy settings / proxy issue
=> so can tell user to fix proxy settings
connectivity issue / web-server down
=> so user is aware of this
server side error (e.g. server is there but there is an issue handling the request - e.g content not there)
=> so user can raise with website manager
success case (and I assume this would be more than just the OK)
=> na (success case)
thanks
In my experience the response status code only returns 200 or 0. Anything else comes through the WebException, including proxy errors like 407 or 417.
The WebException is thrown whenever the web request cannot be executed successfully. For e.g 400 and 500 series of responses.
WebExcpetion has a property named Status which will return the actual status of the response i.e 500 (Internal Server Error).
Here is the list of all response codes: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
===============================================================================
In general:
1xx series of code = provisional response. These are not error codes. For e.g the 100 Continue response which tells that client should continue with its request. Usually WebRequest will not return such response, and handle it itself by sending the rest of request.
2xx series of code = Request was successful received, understood and accepted. These are not error codes. For e.g 200 OK
3xx series of code = Further action needs to be taken. Generally this is not error code (usually its for re-direction) for e.g '301 Moved Permanently', which means that the resource being request is moved to a new location, so any further requests by the client should be on the new URL provided in the response.
OR '305 Use Proxy', which according to you results in an Exception.
4xx series of code = Client errors. These can result in exception. for e.g '400 Bad Request' or '401 Unauthorized'
5xx series of code = Server errors. These can result in exception. for e.g '500 Internal Server Error' or '504 Gateway Timeout'

Categories