从对HttpClient的Web Api请求中获取自定义验证错误消息
本文关键字:自定义 获取 验证 错误 消息 请求 HttpClient Web Api 从对 | 更新日期: 2023-09-27 18:16:36
我的ASP有以下模型:. NET Web Api 2服务:
public class Message
{
public int Id { get; set; }
[Required]
[StringLength(10, ErrorMessage = "Message is too long; 10 characters max.")]
public string Text { get; set; }
}
我正在从我的WinForms应用程序发出请求:
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?
}
我如何看到我在模型类中编写的自定义错误消息?
这是我的实现我的验证类,我注册到web api配置:
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
我弄清楚了,我需要在我的验证类中设置Response.ReasonPhrase
,以便客户端可以看到它(而不仅仅是"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);
}
}
}