【问题标题】:Include a valid field if ModelState state is Invalid如果 ModelState 状态无效,则包含有效字段
【发布时间】:2013-01-19 10:18:41
【问题描述】:

在 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);
        }
    }
}

我是否可以在用户上设置一些东西来指示第三方 ID 应始终包含在返回的错误消息中?

【问题讨论】:

  • 我无法理解您的业务需求。是否需要第三方 ID?
  • 我们可以说是。但是我仍然想在错误消息中返回它,即使它是在发布期间由 API 的使用者发送的。

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


【解决方案1】:

您可以使用 ModelState.AddModelError 方法。

ModelState.AddModelError("VariableName", "Error Message");

【讨论】:

  • 如果我在控制器内部进行验证,那很好,但我想在 ModelValidationFilterAttribute : ActionFilterAttribute 中进行验证,并且对于不同的模型,我想要返回的有效字段会有所不同。
猜你喜欢
  • 1970-01-01
  • 2019-05-06
  • 1970-01-01
  • 2020-03-03
  • 1970-01-01
  • 1970-01-01
  • 2014-05-17
  • 2018-12-04
  • 1970-01-01
相关资源
最近更新 更多