1

I have the following model for my ASP.NET Web Api 2 service:

public class Message
{
    public int Id { get; set; }

    [Required]
    [StringLength(10, ErrorMessage = "Message is too long; 10 characters max.")]
    public string Text { get; set; }
}

I am making the request from my WinForms app:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(BaseAddress);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var messageOverTenCharacters = new Message { Text = "OverTenCharacters" }

    var response = await client.PostAsJsonAsync("api/messenger/PushMessage", messageOverTenCharacters);

    // How do I see my custom error message that I wrote in my model class?
}

How do I see my custom error message that I wrote in my model class?

Here is my implementation for my validation class that I'm registering to the web api config:

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ModelState.IsValid == false)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, actionContext.ModelState);
        }
    }
}
Drake
  • 2,679
  • 4
  • 45
  • 88
  • Does your WebAPI controller action test for validity? – Jasen Oct 07 '15 at 19:50
  • That depends what you did in your controller. What is the implementation of messenger - push message? – Niels V Oct 07 '15 at 19:50
  • 1
    [This may point you in the right direction](http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api) – Joshua Shearer Oct 07 '15 at 19:51
  • I know my controller is testing for validity because the `response` has a 400 status code, and the `response.ReasonPhrase` is "Bad Request" – Drake Oct 07 '15 at 19:54

1 Answers1

1

I figured it out, I needed to set the Response.ReasonPhrase in my validation class so the client can see it (instead of just "BadRequest"):

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ModelState.IsValid == false)
        {
            var errors = actionContext.ModelState
                                      .Values
                                      .SelectMany(m => m.Errors
                                                        .Select(e => e.ErrorMessage));

            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, actionContext.ModelState);

            actionContext.Response.ReasonPhrase = string.Join("\n", errors);
        }
    }
}
Drake
  • 2,679
  • 4
  • 45
  • 88