In C #, if a 500 error (INTERNALSERVERERROR) occurs when you invoke the Web API with HttpClient and read the response content through Content.readasstringasync (), You get a JSON string that contains the error message:
{ "Message":"An error has occurred.", "Exceptionmessage":"", "Exceptiontype":"", "StackTrace":"", "innerexception": { "Message":"", "Exceptionmessage":"", "Exceptiontype":", "StackTrace":"", "innerexception": { "Message":"", "Exceptionmessage":"", "Exceptiontype":"", "StackTrace":"" } }}
Such a complex string is poorly readable, and usually requires only part of the information (such as exceptionmessage) to know the error situation.
So how do you read some of the information you need?
Starting with Microsoft.AspNet.WebApi.Client + dynamic, the implementation code is as follows:
var await await response. Content.readasasync<expandoobject>(); Console.WriteLine (content. Exceptionmessage);
Later on, this JSON string is also serialized out as an instance of some type, it would be simpler to find this type and then deserialize the instance of this type directly.
Looked for, found that the original is Microsoft.AspNet.WebApi.Core in the Httperror:
namespacesystem.web.http{[XmlRoot ("Error")] Public Sealed classhttperror:dictionary<string,Object>, IXmlSerializable { PublicHttperror (); PublicHttperror (stringmessage); PublicHttperror (Modelstatedictionary modelstate,BOOLincludeerrordetail); PublicHttperror (Exception Exception,BOOLincludeerrordetail); Public stringExceptionmessage {Get;Set; } Public stringExceptiontype {Get;Set; } PublicHttperror innerexception {Get; } Public stringMessage {Get;Set; } Public stringMessagedetail {Get;Set; } PublicHttperror Modelstate {Get; } Public stringStackTrace {Get;Set; } PublicTValue getpropertyvalue<tvalue> (stringkey); }}
Instead, use the following simpler implementation code:
var await _httclient.getasync (URL); Console.WriteLine (await response. Content.readasasync
Note: NuGet installation Microsoft.AspNet.WebApi.Client and Microsoft.AspNet.WebApi.Core are required
HttpClient simple way to read ASP. NET WEB API error messages