編集:クラスからの出力をもう少し具体的にし、ステータス コードを変更しました。私はこれらの変更を開始し、後で @CodeCaster の 2 番目のコメントを見ました。
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);
}
}
}