How to Capture Errors When Using Restsharp & System.Text.Json? - c#

I am using RestSharp in my project but when I try to connect to an endpoint. I am getting an error but it is not being captured. The deserialization goes ahead on the object and just returns null instead of throwing an error.
If I was not using deserialization I probably could look at the http status code but that is all hidden.
For instance I have code like ths
var request = new RestRequest("address/update").AddJsonBody(updatedAddress); var response = await client.PostAsync<AddressUpdateResponse>(request);
all I will see in "response" is null. I can't get any other information.
I read this in their error handling section.
WARNING
Please be aware that deserialization failures will only work if the serializer throws an exception when deserializing the response. Many serializers don't throw by default, and just return a null result. RestSharp is unable to figure out why null is returned, so it won't fail in this case. Check the serializer documentation to find out if it can be configured to throw on deserialization error.
I am using System.Text.Json but not sure how to do this.

Related

System.Text.Json.JsonException: The input does not contain any JSON tokens

I'm just trying to use a Http POST method in a Blazor app through
public async Task CreateUnit(UnitEntity unit)
{
await _http.PostJsonAsync<UnitEntity>("api/units", unit);
}
_http and myObject have been defined elsewhere, but I'm getting this weird error. Can anyone help? This is the closest thing I could find elsewhere: https://github.com/dotnet/runtime/issues/30945.
The full error message is
System.Text.Json.JsonException: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
And it here's the stack
Another reason this error could pop up, as it did for me, is simply because the API endpoint doesn't exist because it was misspelled.
I got a similar error in Program.cs Main method CreateHostBuilder(args).Build();:
System.FormatException: 'Could not parse the JSON file.'
JsonReaderException: The input does not contain any JSON tokens.
Expected the input to start with a valid JSON token, when isFinalBlock
is true. LineNumber: 0 | BytePositionInLine: 0.
For me it turned out to be the local secrets.json file that not contained a valid json object.
https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-5.0&tabs=windows#secret-manager
Because of this I could not see any errors in Git or rollback to a working commit since the file is not checked in.
Solved by adding an empty object to the file via Visual Studio - right click the project in solution explorer and select Manage User Secrets:
{
}
https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets?view=aspnetcore-5.0&tabs=windows#manage-user-secrets-with-visual-studio
In my case the code was doing this:
var json = await response.Content.ReadAsStringAsync();
var result = JsonObject.Parse(json); // threw the exception mentioned in the question
Why did that happen? That's because json value was an empty string "". Parse fails with an empty string.
Fixed it doing this simple change:
var json = await response.Content.ReadAsStringAsync();
var result = string.IsNullOrEmpty(json) ? null : JsonObject.Parse(json);
i had similar issue and the problem to check if the json string you are readying is empty, null, or bad formatted. debug to the code line where you are reading data into string before deserialize or serialize call.
I got this error when communicating between two APIs.
request = await req.DeserializeRequestBodyAsync<MyDto>(jsonSerializerOptions);
Turned out the code below did not actually send any values:
httpRequestMessage.Content = JsonContent.Create(myDto);
var httpClient = _clientFactory.CreateClient();
var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage, cancellationToken);
I had to manually specify:
await httpRequestMessage.Content.LoadIntoBufferAsync();
Like this:
httpRequestMessage.Content = JsonContent.Create(myDto);
await httpRequestMessage.Content.LoadIntoBufferAsync();
var httpClient = _clientFactory.CreateClient();
var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage, cancellationToken);
For me, this error occurred when calling FindByNameAsync of UserManager.
Sounds silly, but the database connection string in the appsettings was wrong!
Late answer - but I ran into this using Blazor WebAssembly with Browser Link (trying to get Hot Reload to work). Turns out it's an issue loading the appsettings and Browser Link was expecting the secrets file. I fixed by right clicking the Server project and copy/pasting my appsettings values into the secrets file.
In my case, I was passing the id of my object along with the object itself in the url of the put request to an API and faced the same exception. It turned out that it was not necessary to pass the id (as it was retrieved from the object itself, in fact it was not present in the method signature). Removing the id solved the problem.
This error occurred when communicating between client and web API.
API code:
public async Task<IActionResult> PostAsync(object review)
{
return Ok();
}
Client code:
var res = await _client.PostAsJsonAsync("api/reviews", review);
if (res.IsSuccessStatusCode)
{
var myObject = await res.Content.ReadFromJsonAsync<MyObject>(); //this line threw mentioned error
}
Turned out that the API endpoint was returning something different compared to what I was trying to read from JSON i.e. I was trying to read MyObject but API was returning ActionResult
In my case database column was marked not null and I was passing null in API.

JsonSerializationException from TFS REST API response

I am trying to use the new TFS/VSTS REST APIs with our on-prem TFS 2015 server, and cannot retrieve test runs as the response fails internal validation.
Using client code like the following:
var connection = new VssConnection(serverUri), credentials);
var client = connection.GetClient<TestManagementHttpClient>();
var runs = await client.GetTestRunsAsync("project", planId:183110);
throws a JsonSerializationException in line 3 with the following message:
Required property 'environmentName' not found in JSON. Pathvalue[0].testEnvironment', line 1, position 582.
which is accurate. Checking the response in Fiddler shows that the testEnvironment property only has an environmentId property, no name. I have uploaded a trimmed sample of the response to this gist.
My question is why does TFS not return this value or alternatively, is there a way to force the API SDK to ignore this validation error?
I can reproduce that issue if includeRunDetails parameter is true. I reported a bug here that you can vote it.
The workaround is that you could set includeRunDetails to false to get test runs without details include, then base on the result (test run id) to get a test run with details that you want.
client.GetTestRunByIdAsync

Error Calling DescribeIndexFieldsAsync on AmazonCloudSearchClient

I've confirmed that I have permissions to perform the request.
According to amazon's Cloud Search Dev Troubleshooting Guide the error I'm experiencing is likely due to the .net sdk using the wrong api version. I don't see a way to specify the api version explicitely.
I want to avoid having to manually create the http request.
I want to make the request through the SDK.
I've tried all the available versions of the SDK and all of them give me this error.
I've also tried specifying the request properties in various combinations. Nothing works.
Can anybody give me direction as to how I can resolve this issue?
Expected behavior: return info for all index fields
Actual behavior:
error -
"Result Message:
Amazon.Runtime.AmazonUnmarshallingException : Error unmarshalling response back from AWS. Response Body: {
"message": "Request forbidden by administrative rules",
"__type": "CloudSearchException"
}"
----> System.Xml.XmlException : Data at the root level is invalid. Line 1, position 1.
Code sample:
var _configClient = new AmazonCloudSearchClient(
WebConfigurationManager.AppSettings["CloudSearchAccessKey"],
WebConfigurationManager.AppSettings["CloudSearchSecretKey"],
new AmazonCloudSearchConfig
{
RegionEndpoint = RegionEndpoint.USWest2,
ServiceURL = WebConfigurationManager.AppSettings["CloudSearchUrl"]
});
await _configClient.DescribeIndexFieldsAsync(new DescribeIndexFieldsRequest())
CloudSearch is returning json, which you can see in your response body, and the SDK is trying to unmarshal that into xml. When you make a query directly, you can add &format=xml to get xml results. There should be an analogous option in the SDK.

Get XML body of a 400 or 500 HTTP XML response

Long story short, I am sending an XML HTTP post request to an application server, and I am getting back a response, also in the form of XML HTTP.
I have a test site available to me which allows me to see what the server's actual response is, visually, in the form of XML, but I cannot access this XML from my C# code the way it is.
The XML coming back from the application server in my test case looks like this:
<Error><Message>StringErrorMessage</Message></Error>
However, I have had no luck accessing this basic XML to retrieve the value of "StringErrorMessage" for the creation of a detailed error report.
... More code above, all wrapped in a try{}...
_response = Serializer.DeserializeObject<T>(ObjectRequest.GetResponse().GetResponseStream());
}
catch (System.Net.WebException exceptionParameter)
{
var response = (HttpWebResponse)exceptionParameter.Response;
string webExceptionStatus = exceptionParameter.Message;
_exception = exceptionParameter;
return false;
}
I have consulted
C# - Getting the response body from a 403 error
and
Get response body on 400 HTTP response in Android?
The first link's solution doesn't seem to give me access to the basic XML as part of any response object's properties. I am almost positive that there must be a byte[] in there somewhere (in the response, or in the exception object) that can be converted into a char[], which can be converted to a string, which can be converted to my XML body, but I have not been able to find it. The second link's solution is not exactly viable for me because I have to get the response body back in the form of XML, as it might not be an error, but an object that must be deserialized. This particular side of things, I cannot change.
Any advice would be very much appreciated.
- Eli
EDIT: Just wanted to clarify that my basic code is working okay for non-error situations, and is deserializing the XML just fine. It's when my code encounters a HTTP 400 or an HTTP 500 error, where accessing the XML from the catch statement becomes a problem, because my code immediately throws an exception.
The body of a HTTP message (the XML in your case) can be retrieved with the GetResponseStream method of the HttpWebResponse object you have. And, since it's a stream, you can for instance read it with a StreamReader, like so:
HttpWebResponse myWebResponse; // Get this from whereever you want
Stream responseStream = myWebResponse.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string niceStringForYou = reader.ReadToEnd();
...and from that point on, you can do whatever to it.
If you're absolutely sure it's always gonna be XML you get back from the service, you can probably even use an XmlReader to get XML directly from the stream:
XmlReader foo = XmlReader.Create(responseStream);
Comment to edit: As long as you have the HttpWebResponse object, reading it's response stream (GetResponseStream()) should work. And as you point out in your own code, you can get the HttpWebResponse by looking at (HttpWebResponse)exceptionParameter.Response.

Invalid request handling in OData

Im writing an OData webservice with C# and I need some advice on how to handle invalid requests? An example of an error would be if a customer requested a service on an item they no longer own. I would idealy like to report back to the customer exactly why it is invalid as there are multiple possible reasons.
Many thanks
I would recommend using FaultContracts as part of the OperationContract. You can define them just like DataContracts, and handle exceptions just like a custom exception.
[OperationContract]
[FaultContract(typeof(ItemNotOwned))]
Item GetItem(int ItemId);
You would define ItemNotOwned as a seperate contract definition.
Check it out on MSDN: http://msdn.microsoft.com/en-us/library/ms733841.aspx#Y323
Just throw an exception with the message containing that information. The exception will be serialized to the response sent to the client. If you don't care about the response status code, any exception will do and the client will recieve 500 (Internal Server Error). If you want a specific status code throw an instance of DataServiceException.
Look at using QueryInterceptors and ChangeInterceptors
http://robbincremers.me/2012/01/24/wcf-rest-service-with-odata-and-entity-framework-with-client-context-custom-operations-and-operation-interceptors/

Categories