【问题标题】:POST request without content pass model validation [duplicate]没有内容传递模型验证的 POST 请求 [重复]
【发布时间】:2014-02-20 10:33:47
【问题描述】:

我有一个使用 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 请求时,请求正文中没有任何内容,就好像模型验证没有启动一样。

控制器动作采用具有三个属性的视图模型 - 所有必需的字符串。

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

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

即使请求正文为空,是否有强制模型验证的好方法,从而拒绝此类请求?还是有其他方法可以解决这个问题?

【问题讨论】:

  • 显示你的模型代码
  • @SergeyLitvinov 完成!
  • 刚刚发现 this SO question 处理完全相同的问题,所以我投票结束这个问题。
  • @ChristoferEliasson 如果这是你的问题,你不能删除它吗?
  • @MichaelEdenfield 我可以,但正如in the help section 所提到的,重复的问题通常可以作为其他问题的其他有用答案的路标。由于人们倾向于使用完全不同的词进行提问和搜索,因此覆盖范围越好,程序员同事找到他们正在寻找的答案的几率就越大。因此,我投票决定将问题作为重复问题关闭,而不是一起删除。

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


【解决方案1】:

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

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");
        }
    }
}

【讨论】:

    猜你喜欢
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 2019-08-23
    • 1970-01-01
    • 2018-03-23
    相关资源
    最近更新 更多