以下是我用于应用程序的Model类
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
}
}
}
答案 0 :(得分:0)
尝试使用DisplayAttribute
:
public class APIVesselFilter
{
[Required]
[Display(Name="Vessel is required")]
public Guid VesselID { get; set; }
public Guid? AnchorageID { get; set; }
}
我知道这是使用Html.ValidationSummary
时自定义消息的方法,快速测试显示在操作中检查ModelState时会出现这种情况。
答案 1 :(得分:0)
使用CreateErrorResponse而不是CreateResponse可能会解决您的问题。 我遇到了一个熟悉的问题并且已经解决了。 在你的情况下,这将是
actionContext.Response = actionContext.Request.CreateErrorResponse(APIResponse.SendResponse(RequestStatus.GetValidationFailedMessage(), actionContext.ModelState));