Home > Software design >  c# Api rest get error result string to object
c# Api rest get error result string to object

Time:07-06

I have my Api Rest, and in some point I validate somethings and I use this line to return the answer to client computer: (this is server api rest code)

IDictionary<string, string[]> errors = new Dictionary<string, string[]>();
... some validation code...
return Results.ValidationProblem(errors);

after that in my client program I get the response like this: (this is client program)

string errorData = await response.Content.ReadAsStringAsync();

and my string errorData is like this: (this data is in the string if you print errorData)

{
"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title":"One or more validation errors occurred.",
"status":400,
"errors":{"Fail to login":["Invalid username or password"]}
}

when I try to transform that string into real object the data have the default values of the class (empty values): (client program)

ResultError? error = System.Text.Json.JsonSerializer.Deserialize<ResultError>(errorData);

The ResultError class is like this: (client program)

public class ResultError
        {
            IDictionary<string, string[]> errors = new Dictionary<string, string[]>();
            int status = 0;
            string title = string.Empty;
            string type = string.Empty;
        }

how do I get the correct data? any help will be appreciated...

CodePudding user response:

you have to fix the class by adding getters/setters to properties and no any interfaces, and it is usually is not very good idea to assign default value without any special reasons. You should be always ready that a property can be assigned null or something else, somewhere on the way

public class ResultError
{
         public   Dictionary<string, string[]> errors {get; set}
         public   int status {get; set;}
         public   string title {get; set;}
         public   string type {get; set;}
}
  • Related