【问题标题】:Use Get And Post in the same Controller在同一个控制器中使用 Get 和 Post
【发布时间】:2014-02-13 04:45:45
【问题描述】:

我想将 HttpGet 和 HttpPost 属性用于一种操作方法。但是,我只看到了在单独的操作方法上单独使用属性的示例。

例如:

public ActionResult Index()
    {
        //Code...
        return View();
    }

    [HttpPost]
    public ActionResult Index(FormCollection form)
    {
        //Code...
        return View();
    }

我想要这样的东西:

[HttpGet][HttpPost]
public ActionResult Index(FormCollection form)
{
    //Code...
    return View();
}

我记得在某处看到过这种做法,但不记得在哪里。

【问题讨论】:

    标签: c# asp.net-mvc visual-studio


    【解决方案1】:

    如果你真的想这样做,你可以使用[AcceptVerbs] 属性。 (见this SO question

    这样,您的方法可以处理 GET 和 POST 动词(但不能处理 PUT 等其他动词)

    [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)]
    public ActionResult Index(FormCollection form)
    {
        //Code...
        return View();
    }
    

    如果您希望您的方法处理所有动词,请不要使用任何属性:

    public ActionResult Index(FormCollection form)
    {
        //Code...
        return View();
    }
    

    【讨论】:

    • 谢谢这是我想要的(y)
    猜你喜欢
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 2017-11-11
    • 2020-05-12
    • 2016-01-19
    • 2016-04-21
    相关资源
    最近更新 更多