下面是我使用的應用程序的ModelState ERRORMESSAGE是Web API空
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
}
}
}
儘管此代碼可以回答這個問題,提供了關於如何和/或爲什麼它解決了這個問題將改善答案的長期價值附加的上下文。請閱讀此[如何回答](http://stackoverflow.com/help/how-to-answer)以提供高質量的答案。 – thewaywewere