ModelState Errormessage is Empty in Web API

Following is the Model class that I use for the application

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

        public Guid? AnchorageID { get; set; }

    }

Following is the Validation Filter that will check if the ModelState is Valid and if not valid I will send the error message.

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

Here, Following is the response that I get using the above Model State. Over here the error message is not in a user understandable way and so I have added the ErrorMessage in Require attribute of Vessel and I loop through the errors in ModelState. But my error message is always empty (I checked this using a debugger). What am I missing here so that the error message will be bound directly to the 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": "8nEndObjectnNewtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeednNewtonsoft.Json.Serialization.JsonSerializerInternalReadernVoid 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
    }
  }
}

Try decorating your model property with a DisplayAttribute :

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

    public Guid? AnchorageID { get; set; }

}

I know this is the way to customise your messages when using the Html.ValidationSummary and a quick test showed this comes up when inspecting the ModelState in an action.


using CreateErrorResponse instead of CreateResponse might solve your problem. I faced a smiliar problem and was fixed with that. In your case this will be

actionContext.Response = actionContext.Request.CreateErrorResponse(APIResponse.SendResponse(RequestStatus.GetValidationFailedMessage(), actionContext.ModelState));
链接地址: http://www.djcxy.com/p/67996.html

上一篇: 具有多个视图的Android应用

下一篇: Web API中的ModelState Errormessage为空