编辑:我已经使类的输出更加具体并更改了状态代码。我开始进行这些更改,后来看到@CodeCaster 的第二条评论。
public class ModelStateValidFilterAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
/// <summary>
/// Before the action method is invoked, check to see if the model is
/// valid.
/// </summary>
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext p_context)
{
if (!p_context.ModelState.IsValid)
{
List<ErrorPart> errorParts = new List<ErrorPart>();
foreach (var modelState in p_context.ModelState)
{
foreach (var error in modelState.Value.Errors)
{
String message = "The request is not valid; perhaps it is not well-formed.";
if (error.Exception != null)
{
message = error.Exception.Message;
}
else if (!String.IsNullOrWhiteSpace(error.ErrorMessage))
{
message = error.ErrorMessage;
}
errorParts.Add(
new ErrorPart
{
ErrorMessage = message
, Property = modelState.Key
}
);
}
}
throw new HttpResponseException(
p_context.Request.CreateResponse<Object>(
HttpStatusCode.BadRequest
, new { Errors = errorParts }
)
);
}
else
{
base.OnActionExecuting(p_context);
}
}
}
原始答案:
感谢@CodeCaster 的指针,我正在使用以下内容,它似乎有效:
/// <summary>
/// Throws an <c>HttpResponseException</c> if the model state is not valid;
/// with no validation attributes in the model, this will occur when the
/// input is not well-formed.
/// </summary>
public class ModelStateValidFilterAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
/// <summary>
/// Before the action method is invoked, check to see if the model is
/// valid.
/// </summary>
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext p_context)
{
if (!p_context.ModelState.IsValid)
{
throw new HttpResponseException(
new HttpResponseMessage
{
Content = new StringContent("The posted data is not valid; perhaps it is not well-formed.")
, ReasonPhrase = "Exception"
, StatusCode = HttpStatusCode.InternalServerError
}
);
}
else
{
base.OnActionExecuting(p_context);
}
}
}