[编辑:原始代码段不正确。]
[这篇文章旨在帮助回答我遇到的具体问题,我找到了一个很好的答案。我链接到我关注的示例帖子,然后是给我答案的帖子。然后我发布了我成功使用的代码来生成我实现的结果。]
我在ApiController的输入中实现了一种简单的验证技术。以下代码是可用的,但正如您所看到的,它只提供了一般错误消息。
我找到的答案可以指导我使用这种技术:https://stackoverflow.com/a/19322688/7637275
以下是我开始使用的代码 -
using System.Web.Http;
using System.Web.Routing;
using System.Web.Http.Controllers;
using System.Web;
using System.Web.Http.Filters;
namespace TestValidation
{
internal class ValidateModelStateFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
throw new HttpException(422, "Validation failed on input");
}
}
}
}
以下代码段显示了我需要查看的验证错误,而不是上面提到的通用消息。
[Required(ErrorMessage = @"Parameter ""ID"" is required.")]
[MaxLength(18, ErrorMessage = @"Exceeded max length (18 characters) for parameter ""ID""")]
public string ID { get; set; }
此时,在我的覆盖中,我需要深入了解HttpActionContent对象“actionContext”以找到自定义的错误消息。
答案 0 :(得分:0)
[编辑:原始代码段不正确。]
我发现了一个很棒的答案,帮助我解决了我的问题!以下链接将带您回答: https://stackoverflow.com/a/33009722/7637275
以下是我用来从我的网络服务提供自定义验证消息的结果代码。我做了三个小调整。我选择实现一个Try / Catch块,如果代码失败,它只提供一般错误消息。我使用了List而不是var(编码风格)。我还使用了分号而不是换行来加入错误(这符合我的要求)。
非常感谢stackoverflow中的两张海报帮助我了解了这一点!
using System.Web.Http;
using System.Web.Routing;
using System.Web.Http.Controllers;
using System.Web;
using System.Web.Http.Filters;
using System.Linq;
using System.Collections.Generic;
namespace TestValidation
{
internal class ValidateModelStateFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
string errorMessage = string.Empty;
List<string> errors = new List<string>();
try
{
errors = actionContext.ModelState.Values.SelectMany(val => val.Errors.Select(err => err.ErrorMessage)).ToList();
errorMessage = string.Join(";", errors);
}
catch {
errorMessage = "Validation failed on input";
}
throw new HttpException(422, errorMessage);
}
}
}
}