2

I have an APS.NET Core 2.0 API that I am writing a test client for. The test client is a console application. I want to be able to read and display any errors returned from may API call that would be in the model state.

In my API, if the model is not valid, I return the model along with a status 422 as follows;

        if (!ModelState.IsValid)
        {
            return new UnprocessableEntityObjectResult(ModelState);
        }

The UnprocessableEntityObjectResult is just a helper class, as shown below;

public class UnprocessableEntityObjectResult : ObjectResult
 {
     public UnprocessableEntityObjectResult(ModelStateDictionary modelState)
          : base(new SerializableError(modelState))
     {

         if (modelState == null)
         {
             throw new ArgumentNullException(nameof(modelState));
         }

         StatusCode = 422;
     }
 } 

My intent is to return the modelstate to the client, on error.

My test client is a console application and I am looking for a way to examine the model state and list out any errors.

In my console application, I have the following method that is called from Main;

    static async Task CreateUploadRecordAsync()
    {

        httpClient.BaseAddress = new Uri("https://localhost:44369");
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        string relativeUrl = "/api/upload";

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, relativeUrl);

        HttpResponseMessage response = new HttpResponseMessage();


        using (var content = new MultipartFormDataContent())
        {
            //Add content values here...
            request.Content = content;
            response = await httpClient.SendAsync(request);
        }

        if (response.IsSuccessStatusCode)
        {
            string result = response.Headers.Location.ToString();
            Console.WriteLine("Success:\n");
            Console.WriteLine($"New Record Link: [{result}]\n");
        }
        else
        {

            //Add code here to get model state from response

            Console.WriteLine($"Failed to create new upload record. Error:  {response.ReasonPhrase}\n");
        }

    }

I am looking for an example of how to extract the model state that would exist after the "/Add code here to get model state from response" comment.

Any ideas?

EiEiGuy
  • 1,447
  • 5
  • 18
  • 32

0 Answers0