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?
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With