我们使用 WebApi v2.1 并通过 WebApiConfig 类中应用的过滤器验证 ModelState。
当我们在服务器(Win Server 2008R2)上运行时,错误消息中不会列出按要求指定的字段,但当我们在本地(在 IISExpress 上)运行时,它们可以正常工作。
请求在本地和服务器上被正确拒绝,但服务器响应不显示丢失的字段。
例如: 如果本地请求缺少必需的缩写和 IssuerName 字段,则响应将按预期显示:
{ "message": "The request is invalid.", "modelState": { "value": [ "Required property 'abbreviation' not found in JSON. Path '', line 18, position 2.", "Required property 'issuerName' not found in JSON. Path '', line 18, position 2." ] }
当向服务器发送相同的请求时,响应显示:
{ "message": "The request is invalid.", "modelState": { "value": [ "An error has occurred.", "An error has occurred." ] } }
我们的过滤器如下:
public class ValidateModelStateAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
} } }
我们的数据模型类用 DataContract 属性修饰,所需字段的属性如下:
[DataMember(IsRequired=true)]
public string IssuerName
最佳答案
服务器对于向客户端发送错误有更多限制。尝试在 httpconfiguration 上设置 IncludeErrorDetails
标志,以验证这是否是根本问题。
一般来说,尽管打开此标志不是最好的主意,并且您会希望以不同的方式序列化错误。
欲了解更多信息: http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx
关于asp.net-web-api - WebApi 2.1 模型验证在本地工作,但在服务器上运行时不显示缺失的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23351088/