繁体   English   中英

处理ASP.NET MVC中的post请求

[英]Handling post requests in ASP.NET MVC

最近我开始使用MVC,之前我使用了“经典”ASP.NET。

在使用Ruby on Rails(RoR)之后,我想知道如何在MVC中实现类似于RoR操作的POST请求处理。 在RoR中,您使用Post方法,因此视图只需要一个函数。

在ASP.NET MVC中,我需要为GETPOST使用2个单独的函数,所以我需要初始化相同的数据两次,我不想在我的代码中重复一些东西。

如何在一种方法中检查请求是否为POST

更新:

找到解决方案:我必须使用Request.HttpMethod。

谢谢!

我遇到了这个想要知道同样事情的问题。 下面是我的情况和我使用的解决方案的详细描述(利用此处提供的其他答案)。 我最初尝试使用两种单独的方法方法,但是当这些方法的方法签名变得相同时,我遇到了问题。

我有一个显示报告数据的页面。 在页面顶部有一个包含一些字段的表单,允许用户指定报告参数,如开始日期,结束日期等。

我最初通过创建两个单独的方法来处理Get和Post方法来解决这个问题。 post方法会将浏览器重定向到get方法,以便指定的任何参数都会添加到查询字符串中,这样浏览器就不会提示用户说明它将重新发送他们输入的数据如果他们刷新 注意:后来我意识到我可以通过将我的表单元素的method属性设置为“Get”来实现这一点,但我认为理想情况下控制器不应该知道如何实现视图,所以在我看来这是无关紧要的。

当我开发这两种方法时,我最终发现自己处于方法签名变得相同的情况。 此外,我对这两种方法的代码几乎完全相同,所以我决定将它们合并到一个方法中,只检查请求动词,这样当请求不是“获取”时我可以做一些稍微不同的事情。 我的两种方法的蒸馏示例如下所示:

    // this will not compile because the method signatures are the same

    public ActionResult MyReport(DateRangeReportItem report)
    {
        // if there are no validation errors and the required report parameters are completed
        if (ModelState.IsValid && report.ParametersAreComplete)
        {
            // retrieve report data and populate it on the report model
            report.Result = GetReportData(report.CreateReportParameters());
        }

        return View(report);
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult MyReport(DateRangeReportItem report)
    {
        if (ModelState.IsValid && report.ParametersAreComplete)
        {
            // redirect to the same action so that if the user refreshes the browser it will submit a get request instead of a post request
            // this avoids the browser prompting the user with a dialog saying that their data will be resubmitted
            return RedirectToAction("MyReport", new { StartDate = report.StartDate, EndDate = report.EndDate });
        }
        else
        {
            // there were validation errors, or the report parameters are not yet complete
            return View(report);
        }
    }

为什么我接受模型对象作为我的get方法的参数? 原因是我想利用已经内置到模型对象中的验证逻辑。 如果有人直接使用查询字符串中已指定的所有参数导航到我的页面,那么我想继续检索报告数据并将其显示在页面上。 但是,如果查询字符串中指定的参数无效,那么我还希望在页面上显示验证错误。 通过将我的模型对象作为参数,MVC框架将自动尝试填充它并捕获任何验证错误,而无需我做任何额外的工作。

我使用为此问题发布的其他答案在我的项目中的基本控制器类上创建RequestHttpVerb属性:

    public HttpVerbs RequestHttpVerb
    {
        get { return (HttpVerbs)Enum.Parse(typeof(HttpVerbs), this.Request.HttpMethod, true); }
    }

所以最后我的整合方法如下所示:

    [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
    public ActionResult MyReport(DateRangeReportItem report)
    {
        // check if there are any validation errors in the model
        // and whether all required report parameters have been completed
        if (ModelState.IsValid && report.ParametersAreComplete)
        {
            // this is unnecessary if the form method is set to "Get"
            // but within the controller I do not know for sure if that will be the case in the view
            if (HttpVerbs.Get != this.RequestHttpVerb)
            {
                // redirect to the same action so that if the user refreshes the browser it will submit a get request instead of a post request
                // this avoids the browser prompting the user with a dialog saying that their data will be resubmitted
                return RedirectToAction("MyReport", new { StartDate = report.StartDate, EndDate = report.EndDate });
            }

            // there were no validation errors and all required report parameters are complete
            // retrieve report data and populate that data on the model
            report.Result = GetReportData(report.CreateReportParameters());
        }

        // display the view with the report object
        // Any model state errors that occurred while populating the model will result in validation errors being displayed
        return View(report);
    }

这是我目前解决问题的方法。 我宁愿不必检查Request.HttpMethod属性以确定是否需要执行重定向,但我没有看到我的问题的另一个解决方案。 我可以保持两个单独的方法来处理Get和Post请求,但是相同的方法签名阻止了这一点。 我本来希望重命名我的Post动作处理程序方法以避免方法签名冲突并使用某种机制向MVC框架指示我的重命名方法仍然应该处理“MyReport”动作,但我不知道任何这样的机制在MVC框架中。

如果他们的方法签名不同,你只需要单独的GET和POST方法,没有理由为什么一个动作方法不能处理GET和POST方法。

如果您需要知道它是GET还是POST,您可以在动作中使用Request.HttpMethod进行检查,但我建议使用其他海报建议的[AcceptVerbs(HttpVerbs.Post)]属性修饰的单独方法。 。

您没有签入ASP.NET MVC。 您使用[AcceptVerbs(HttpVerbs.Post)]属性装饰您的方法,以指示该方法仅适用于post,并接受用于处理帖子的方法中的模型。

我强烈建议为NerdDinner进行演练,以了解有关ASP.NET MVC框架的更多信息。

您可以查看Request.HttpMethod属性。

正确的方法是在Post请求期间使用ModelBinding。

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(EmployeeViewModel model)
{
 //validate data, save employee, handle validation errors...
}

这样您就不必再次初始化数据了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM