Drake
Drake

Reputation: 2703

Get custom validation error message from Web Api request to HttpClient

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);
        }
    }
}

Upvotes: 1

Views: 3872

Answers (1)

Drake
Drake

Reputation: 2703

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);
        }
    }
}

Upvotes: 1

Related Questions