c# - 没有内容的 POST 请求通过模型验证

标签 c# asp.net asp.net-web-api model-validation

<分区>

我有一个使用 Web API 2 的 ASP.NET 应用程序。

为了强制对所有操作进行模型验证,我使用了一个过滤器,如下所示:

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, actionContext.ModelState);
        }
    }
}

这在大多数情况下效果很好,但是当我针对 API 端点执行 POST 请求而请求正文中没有任何内容时,就好像模型验证没有启动一样。

Controller Action 采用具有三个属性的 View 模型 - 所有必需的字符串。

public class AddEntityViewModel
{
    [Required]
    public string Property1 { get; set; }
    [Required]
    public string Property2 { get; set; }
    [Required]
    public string Property3 { get; set; }
}

如果我只是添加一些随机数据作为请求主体,模型验证会按预期启动并拒绝请求,但如果请求主体完全为空,则模型验证通过并且我在操作中获得的模型为空。

有没有什么好的方法可以在请求体为空的情况下强制进行模型验证,从而拒绝此类请求?或者有其他方法可以解决这个问题吗?

最佳答案

我最终做的是扩展我的模型验证过滤器以验证模型不为空。

public class ValidateModelAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, actionContext.ModelState);
        } 
        else if (actionContext.ActionArguments.ContainsValue(null))              
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(
                HttpStatusCode.BadRequest, "Request body cannot be empty");
        }
    }
}

关于c# - 没有内容的 POST 请求通过模型验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21905098/

相关文章:

c# - 当线程使用调度程序并且主线程正在等待线程完成时出现死锁

c# - 为什么不允许指向泛型类型的指针?

asp.net - asp.net 中的 View 状态和文本框

c# - 这个左外连接查询的正确 Linq 表达式是什么?

c# - 自托管 ASP.NET Web API 的 SSL 证书绑定(bind)在重启后丢失

c# - MVC4 webapi 中的反序列化/模型绑定(bind)不适用于数组

c# - 自动将 LinqToSql 基类添加到实体的方法?

c# - 在 2D map 上查找满足多个条件的位置

javascript - $find() 对于定义的 ajax 行为返回 null

javascript - 任务取消异常 : a task was cancelled while rendering jsreport