从Web Api请求到HttpClient获取自定义验证错误消息 [英] Get custom validation error message from Web Api request to HttpClient
本文介绍了从Web Api请求到HttpClient获取自定义验证错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的ASP.NET Web Api 2服务具有以下模型:
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; }
}
我正在从我的WinForms应用程序发出请求:
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?
这是我正在向Web api配置注册的验证类的实现:
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);
}
}
}
推荐答案
我知道了,我需要在验证类中设置Response.ReasonPhrase
,以便客户端可以看到它(而不仅仅是"BadRequest"):
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);
}
}
}
这篇关于从Web Api请求到HttpClient获取自定义验证错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文