asp.net-web-api - WebApi 2.1 模型验证在本地工作,但在服务器上运行时不显示缺失的字段

标签 asp.net-web-api

我们使用 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/

相关文章:

asp.net-web-api - 不同应用程序域中的 Web API Controller

javascript - 我们能确定MVC EnableCors的由来吗?

c# - 从另一个 Web api 调用一个 Web api

ios - 映射到核心数据(命名不一致的 Web API)

javascript - 将数组从 AngularJS 传递到 Web API 并从 Web API 读取

c# - ASP.Net WebApi : How to load additional controllers at runtime

c# - 如何根据 ID 列表对 EF 返回的对象进行排序?

asp.net - 将 ADFS token 传递给服务

docker - .Net Core Dockerized WebAPI 无法注册到 Eureka 服务器

c# - ASP.NET MVC4 Web API MediaTypeFormatter Converter 将 XElement 转换为 JSON