Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ModelState to return errors from WebAPI 2

I am trying to use ModelState object to send Errors to the Client; I am using asp.net Web API for the Service.

On the Web Service side, I am doing this.

    public HttpResponseMessage VerifyData(Cobject data)
    {
        string[] errors;
        if (!VerifyAllRequiredData(data, out errors))
        {
            foreach(string error in errors)
                ModelState.AddModelError("", error);
            return Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, ModelState);
        }

        return Request.CreateResponse(HttpStatusCode.OK, data);
    }

I am creating a .NET Client library for the service so we can use it for exsiting windows applications.

on the client side:

    public bool VerifyData(Cobject data)
    {
        try
        {  
            HttpClient c = new HttpClient();
            c.BaseAddress = BaseAddress;
            c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(JsonHeader));
            c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(HTMLHeader));
            c.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(TextHeader));
            var asyncResponse = this.PostAsJsonAsync(url, data);
            asyncResponse.Wait();
            asyncResponse.Result.EnsureSuccessStatusCode();
            return true;
        }
        catch (HttpRequestException hre)
        {
            Console.WriteLine(hre.Message);
            return false;
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            return false;
        }
    }

The problem here is I don't see any messages that were added to the ModelState on the respose. I see the status(ExpectionFailed) but no messages. How do I retrive those messages on the client?

like image 979
katie77 Avatar asked Mar 09 '14 22:03

katie77


1 Answers

I use a "similar" code to make posts and gets to my web api. Let me copy some code so you can get the information from the ModelState

var responseTask = await client.SendAsync(request);
var result = responseTask.ContinueWith(async r =>
               {
                   var response = r.Result;

                   var value = await response.Content.ReadAsStringAsync();
                   if (!response.IsSuccessStatusCode)
                   {
                       var obj = new { message = "", ModelState = new Dictionary<string,string[]>() };
                       var x = JsonConvert.DeserializeAnonymousType(value, obj);
                       throw new AggregateException(x.ModelState.Select(kvp => new Exception(string.Format("{0}: {1}", kvp.Key, string.Join(". ", kvp.Value)))));
                   }

               }).Result;

I hope this do the trick for you :)

like image 141
JLuis Estrada Avatar answered Sep 21 '22 15:09

JLuis Estrada