ModelState.IsValid返回400 Bad Request

时间:2014-09-16 10:41:52

标签: c# asp.net asp.net-mvc asp.net-mvc-5

在ASP.NET MVC 5应用程序中,如果ModelState验证失败,以下代码应该将用户发回原始视图。

将向用户显示与验证失败的输入相关的错误消息。

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(DemoViewModel model)
{
    if (!ModelState.IsValid) return View(model);

    ...

    return RedirectToAction("Details");
}

但是,目前,当我的ModelState无效时,我收到400错误请求错误页面:

IE
IE


Chrome

最初,我认为这是自定义错误页面的错误配置。 为了排除这一点,我创建了一个具有相同错误页面配置的新项目,我无法重新创建问题。

仅供参考,这是错误配置:

Web.config客户错误

<customErrors mode="On" defaultRedirect="~/500.aspx" redirectMode="ResponseRewrite">
    <error statusCode="401" redirect="~/401.aspx" />
    <error statusCode="403" redirect="~/401.aspx" />
    <error statusCode="404" redirect="~/404.aspx" />      
</customErrors>

Web.config httpErrors

<httpErrors errorMode="Custom" >
    <remove statusCode="401" />
    <error statusCode="401" path="401.html" responseMode="File" />
    <remove statusCode="403" />
    <error statusCode="403" path="401.html" responseMode="File" />
    <remove statusCode="404" />
    <error statusCode="404" path="404.html" responseMode="File"/>
    <remove statusCode="500" />
    <error statusCode="500" path="500.html" responseMode="File" />
</httpErrors>

什么可能打破ModelState的处理方式?

2 个答案:

答案 0 :(得分:0)

您正在控制器操作中触发GET请求,但它需要POST。这导致错误代码400。

您可能希望重定向到显示要编辑的对象的“编辑”操作。

假设您的ViewModel中有Id并且您的修改操作需要int Id,请执行以下操作:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(DemoViewModel model)
{
    int modelId = model.Id;
    if (!ModelState.IsValid) {
       //call the Edit action which displays the item .. or details. 
       //Not an ActionResult decorated as [HttpPost]!
       return RedirectToAction("EditGetAction", new { id = modelId });
    }

    ...

    return RedirectToAction("Details");
}

答案 1 :(得分:0)

我找到了问题的原因。

导致错误的页面有2个表单,一个只在模态中可见,而我正在尝试调试的主表单。 我错误地认为主要形式是导致问题的形式,实际上,它是隐藏的形式,它将以模态显示。

经过大量调试后,我在另一个动作中找到了一行代码,而不是我认为导致问题的代码。

感谢那些提出建议的人。