Get custom validation error message from Web Api request to HttpClient

岁酱吖の 提交于 2019-12-08 04:51:07

问题


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

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


来源:https://stackoverflow.com/questions/33001134/get-custom-validation-error-message-from-web-api-request-to-httpclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!