0

在 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 包含在返回的错误消息中吗?

4

1 回答 1

0

您可以使用 ModelState.AddModelError 方法。

ModelState.AddModelError("VariableName", "Error Message");
于 2013-02-04T17:55:05.787 回答