如果ModelState状态为Invalid,则包括有效字段

时间:2013-02-04 16:52:07

标签: c# asp.net-mvc validation asp.net-web-api modelstate

在ASP.NET Web API中,我希望在向调用者返回错误时包含有效字段。

public class User 
{
    [Required(ErrorMessage = "ThirdPartyID is required!")]
    public int ThirdPartyID { get; set; }
    [Required(ErrorMessage = "Firstname is required!")]
    public string Firstname { get; set; }
    [Required(ErrorMessage = "Lastname is required!")]
    public string Lastname { get; set; }
}

当调用者发布设置了ThirdParyID并设置了Firstname但没有Lastname的用户时,我想将ThirdPartyID添加到响应中。我使用下面的模型验证。

public class ModelValidationFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.ModelState.IsValid == false)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
        }
    }
}

我可以在User上设置一些东西来指示ThirdPartyID应该总是包含在返回的错误消息中吗?

1 个答案:

答案 0 :(得分:0)

您可以使用ModelState.AddModelError方法。

ModelState.AddModelError("VariableName", "Error Message");
相关问题