HttpResponseMessage not returning 400 Bad Response - c#

I have a method within a project that checks the Http response of a URL, called ValidateAcsUrl.
In the method, the Http response of the URL is checked, and returned as a string.
The URLs I am testing have responses of:
200 OK
400 Bad Request
404 Not Found
500 Internal Server Error
And in the catch exception, if the response does not work then an "Unavailable" response is returned
All of the responses work, apart from the 400 Bad Request.
An example of a working URL is shown below, in debug mode.
The 400 Bad Request response URL (using Appending/%, after a working URL) jumps from the HttpResponseMessage line into the catch exception, which returns "Unavailable".
Does HttpResponseMessage not work with a 400 Bad Request, or is there something else I have to do?

Related

How can i retrieve the http response status code from an url?

I am automating a test for a page that contains a URL that needs to be then tested.
I created a method that I believed was giving me the http status code:
public string ContentUrlHttpRequest()
{
HttpWebRequest protocolWebRequest = (HttpWebRequest)WebRequest.Create(ContentUrl());
protocolWebRequest.Method = "GET";
HttpWebResponse response = (HttpWebResponse)protocolWebRequest.GetResponse();
return response.Headers.ToString();
}
ContentUrl() is another method i created to find the element on the page with the url to be tested and gets it's value.
I have also tried return response.StatusCode.ToString(); but the response i received was "OK".
I know that the response from that url needs to be = 200. I have this assertion that compares the response from the ContentUrlHttpRequest() to the expected results (200):
Assert.AreEqual("200", ContentUrlHttpRequest(), "The Url is not live. Http response = " + ContentUrlHttpRequest());
The response i am getting from ContentUrlHttpRequest() is not the status code but:"Date: Mon, 03 May 2021 09:07:13 GMT".
I understand why it is happening, it is getting the header of the page that is searching. But how could I get the status code? Is it possible with Selenium? Is there something wrong with my method and instead of Headers I need to use something different?
Unfortunately i am not able to provide with the urls that i am testing, or the platform with the url as they are confidential. Hopefully my issue is clear and you guys can give me some guidance.
You are not returning the response status code. You are returning the headers.
You should replace the return statement with this:
return ((int)response.StatusCode).ToString();
I guess you should use response.Status.ToString(); instead of response.Headers.ToString();
But the status contains not only the number like 200 or 401 but also text.
So if you are going to use response.Status.ToString(); you should Assert.True(ContentUrlHttpRequest().contains("200"))
Or you can use response.StatusCode.ToString(); this will give you the status number itself String without additional texts.

Why does Firefox have a problem with this 204 (No Content) response?

I'm calling a WebAPI controller from jQuery AJAX to request an item be deleted via a REST API.
The WebAPI controller returns a 204 (No Content) response, which then invokes a second request (GET). For this example I expect both requests to receive a 204 (No Content) response.
When viewed in Chrome both responses are fully recognised.
However, Firefox can't seem to cope with a 204 if it contains no content.
To obtain both the Chrome (above) and Firefox (below) screenshots the same requests were sent to a WebAPI controller from both browsers. The screenshot below shows that Firefox only recognises the first 204 response.
The response to these two requests is created differently:
The first response uses...
return Request.CreateResponse(HttpStatusCode.NoContent);
...which returns an instance of HttpResponseMessage.
The second response uses...
return new NoContentResult();
...which we've defined as an implementation of IHttpActionResult...
public class NoContentResult : IHttpActionResult
{
private readonly HttpRequestMessage _request;
public NoContentResult(HttpRequestMessage request)
{
_request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = _request.CreateResponse(HttpStatusCode.NoContent, new StringContent("{}"));
return Task.FromResult(response);
}
}
The new StringContent("{}") on the 4th-from-last line is an attempt to provide some content to help Firefox. I've also tried new StringContent("null") with the same result.
Also, if that second response is inspected in Firefox, the following error message is found:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of
the JSON data
It seems that Firefox is trying to parse this problematic 204, but it apparently makes no attempt to parse the first 204 response.
Furthermore, the request type (DELETE vs. GET) doesn't seem to matter: if I return 204 as an IHttpActionResult from the first call then Firefox still doesn't like it.
Firefox also displays the first response as containing 168 bytes and the second as containing 0 bytes even though it will happily display the headers (below). Firefox is clearly upset at something.
Can anyone explain why Firefox has a problem with a 204 response when delivered as an implementation of IHttpActionResult but not when it's delivered as an HttpResponseMessage?
[The reason that the first request returns an HttpResponseMessage while the second returns an IHttpActionResult is that the first method has been in place for a long time whereas the second method is only now being added. And as IHttpActionResult is easier to test, we'd like to use that.]

System.AggregateException on GetStringAsync in asp.net

I am trying to call an API like this:
var client = new HttpClient();
client.DefaultRequestHeaders.Add("apiKey", Token);
**var result = await client.GetStringAsync(GetUrl($"accounts/{accountID}/menu?skip=0&limit=1"));**
var menuList = JsonConvert.DeserializeObject<List<Menu>>(result);
but getting System.AggregateException on GetStringAsync, error CS0103: The name 'InnerExceptionCount' does not exist in the current context
and Exception Message
One or more errors occurred. (Response status code does not indicate success: 404 (Not Found).)
I see that this is returned in result
Status = WaitingForActivation, Method = "{null}", Result = "{Not yet computed}
I tried to make call using postman with same url and apikey in header and I see the results.
Can you please suggest what is wrong with above code. Api key expects only an apiKey in header.
Thanks.
Anytime that an async call fails you'll get an AggregateException, what's important is the inner exception within that.
It looks like your inner exception is 404 Not Found, which means that you're not calling the correct URL.
You said it's working in postman, that's great. To find the root cause I suggest the following:
Start Fiddler
Make the call through postman, view the request in Fiddler
Make the call through your C# code, view the request in Fiddler
Comparing the Postman request against the C# request should tell you where the error is.

HttpWebRequest.GetResponse() , does every StatusCode besides 200 throws exception?

Calling GetResponse() on an httpWebRequest,
In all my testing i saw that this call throws WebException when the request fail.
My question is why is there a StatusCode property on the HttpWebResponse ?
It seems that the GetResponse() call will only return responses with status code 200 and throw otherwise.
And should i even bother looking if the StatusCode is not 200 ?
Assuming the only thing i can do with this information is throw exception myself ...
The entire 2xx range means that the operation has completed successfully. Status code 201 for instance, indicates that a new resource has been created.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for a list of all common status codes.

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