Specific Cast is not valid

jareyes2024

New member
Joined
Feb 13, 2024
Messages
2
Programming Experience
Beginner
I'm making a call to an API and I can't find the source of this error "Specified Cast is not valid"
C#:
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, UrlApi);
request.Headers.Add("Accept", "text/plain");
request.Headers.Add("Authorization", $"Bearer {App.TokenLoged}");

//when this line is executed it gives me the error
var response = await client.SendAsync(request);

response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
 
Last edited by a moderator:
That's odd. There's no casting on that line. Can you view the full exception details and look at the callstack? Perhaps the casting is happening deeper in the code.

Alternatively, that await may actually be yielding to another thread while this asynchronous call is happening. The code that has the casting maybe happening in that other thread.
 
That's odd. There's no casting on that line. Can you view the full exception details and look at the callstack? Perhaps the casting is happening deeper in the code.

Alternatively, that await may actually be yielding to another thread while this asynchronous call is happening. The code that has the casting maybe happening in that other thread.

It does not enter the try catch when the error occurs.
 
No need to change your code to have a try-catch. Just let the debugger show you the call stack.
 
Every exception has a stack trace so will tell you exactly where it was thrown. If you're using the debugger and it is set to break on a thrown exception, it will show you exactly which line is at fault. This is information that you be providing us by default when asking such a question. If you don't know how to debug properly then you should stop what you're doing and learn that first. It's an essential skill for any developer and learning now will save you a lot of time that will be repaid soon enough.
 
Back
Top Bottom