【问题标题】:MVC - How to avoid action returning 404 if not POSTMVC - 如果不是 POST,如何避免操作返回 404
【发布时间】:2012-10-12 09:42:37
【问题描述】:

我在控制器中有两个动作:

    public ActionResult ReportRequest()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Report(ReportRequestObj rr, FormCollection formValues)
    {
        if (Request.HttpMethod != "POST")
            return RedirectToAction("ReportRequest");

        ReportingEngine re = new ReportingEngine();

        Report report = re.GetReport(rr);

        return View(report);
    }

我的问题是,“报告”页面的 URL 保存在浏览器中,当我点击它时,我得到一个 404,因为请求尚未发布。

我放入了一个处理程序以重定向到报告请求页面,但是在调试时它似乎根本没有遇到这个问题。

有没有其他方法可以确定请求是否为帖子,如果不是则重定向回另一个页面?

谢谢

【问题讨论】:

  • 删除方法顶部的 [HttpPost],您可以检查 if (Request.HttpMethod != "POST") return RedirectToAction("ReportRequest");它是否应该返回。

标签: c# asp.net-mvc http-post


【解决方案1】:

添加操作

public ActionResult Report()
{
    return RedirectToAction("ReportRequest");
}

或者只是从动作Report中删除[HttpPost]

【讨论】:

    【解决方案2】:

    您无法在此处处理 404 错误,因为该请求永远不会到达您的操作。您正在使用一个动作过滤器来确保只有 POST 请求到达那段代码。

    您应该创建另一个操作方法来响应 GET 请求并在其中返回您的视图。

    [HttpGet]
    public ActionResult Report()
    {
        return View("ReportRequest");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      • 1970-01-01
      • 1970-01-01
      • 2011-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多