【问题标题】:ModelState Errormessage is Empty in Web APIWeb API 中的 ModelState 错误消息为空
【发布时间】:2017-06-26 20:56:47
【问题描述】:

以下是我用于应用程序的模型类

 public class APIVesselFilter
    {
        [Required(ErrorMessage = "Vessel is required")]
        public Guid VesselID { get; set; }

        public Guid? AnchorageID { get; set; }

    }

以下是验证过滤器,它将检查 ModelState 是否有效,如果无效,我将发送错误消息。

 public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ModelState.IsValid == false)
            {
                List<string> errorList = new List<string>();
                foreach (var err in actionContext.ModelState.Values)
                {

                    foreach (var er in err.Errors)
                    {
                        errorList.Add(er.ErrorMessage);
                    }
                }
                actionContext.Response = actionContext.Request.CreateResponse(APIResponse.SendResponse(RequestStatus.GetValidationFailedMessage(), actionContext.ModelState));
            }
        }
    }

这里,以下是我使用上述模型状态得到的响应。在这里,错误消息不是用户可以理解的,因此我在 Vessel 的 Require 属性中添加了 ErrorMessage,并循环遍历 ModelState 中的错误。但是我的错误消息总是空的(我使用调试器检查了这个)。我在这里遗漏了什么,以便将错误消息直接绑定到 ModelState?

{
  "Status": {
    "StatusCode": 620,
    "StatusMessage": "Validation Failed"
  },
  "Data": {
    "filter": {
      "_errors": [
        {
          "<Exception>k__BackingField": {
            "ClassName": "Newtonsoft.Json.JsonSerializationException",
            "Message": "Required property 'VesselID' not found in JSON. Path '', line 1, position 56.",
            "Data": null,
            "InnerException": null,
            "HelpURL": null,
            "StackTraceString": "   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EndObject(Object newObject, JsonReader reader, JsonObjectContract contract, Int32 initialDepth, Dictionary`2 propertiesPresence)",
            "RemoteStackTraceString": null,
            "RemoteStackIndex": 0,
            "ExceptionMethod": "8\nEndObject\nNewtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed\nNewtonsoft.Json.Serialization.JsonSerializerInternalReader\nVoid EndObject(System.Object, Newtonsoft.Json.JsonReader, Newtonsoft.Json.Serialization.JsonObjectContract, Int32, System.Collections.Generic.Dictionary`2[Newtonsoft.Json.Serialization.JsonProperty,Newtonsoft.Json.Serialization.JsonSerializerInternalReader+PropertyPresence])",
            "HResult": -2146233088,
            "Source": "Newtonsoft.Json",
            "WatsonBuckets": null
          },
          "<ErrorMessage>k__BackingField": ""
        }
      ],
      "<Value>k__BackingField": null
    }
  }
}

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-web-api


    【解决方案1】:

    尝试使用DisplayAttribute 装饰您的模型属性:

    public class APIVesselFilter
    {
        [Required]
        [Display(Name="Vessel is required")]
        public Guid VesselID { get; set; }
    
        public Guid? AnchorageID { get; set; }
    
    }
    

    我知道这是在使用 Html.ValidationSummary 时自定义消息的方法,并且快速测试表明在操作中检查 ModelState 时会出现这种情况。

    【讨论】:

      【解决方案2】:

      使用 CreateErrorResponse 而不是 CreateResponse 可能会解决您的问题。 我遇到了一个类似的问题,并解决了这个问题。 在你的情况下,这将是

      actionContext.Response = actionContext.Request.CreateErrorResponse(APIResponse.SendResponse(RequestStatus.GetValidationFailedMessage(), actionContext.ModelState));
      

      【讨论】:

      • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。请阅读此how-to-answer 以提供高质量的答案。
      最近更新 更多