【问题标题】:MVC4 Ignoring [HttpGet] and [HttpPost] attributesMVC4 忽略 [HttpGet] 和 [HttpPost] 属性
【发布时间】:2012-10-18 09:53:56
【问题描述】:

我正在尝试制作一个简单的测试网站,以允许我使用 MVC4 列出、创建、编辑和删除客户对象。

在我的控制器内部,我有 2 个创建方法,一个用于在表单加载控件时使用的 Get,以及一个用于实际保存数据的 Post。

    //
    // GET: /Customer/Create

    [HttpGet]
    public ActionResult Create()
    {
        return View();
    }

    //
    // POST: /Customer/Create

    [HttpPost]
    public ActionResult Create(Customer cust)
    {
        if (ModelState.IsValid)
        {
            _repository.Add(cust);
            return RedirectToAction("GetAllCustomers");
        }

        return View(cust);
    }

但是,当我运行项目并尝试访问创建操作时,我收到一个错误:

The current request for action 'Create' on controller type 'CustomerController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Create() on type [Project].Controllers.CustomerController
System.Web.Mvc.ActionResult Create([Project].Models.Customer) on type [Project].Controllers.CustomerController

我知道它看不到我的 Get 和 Post 方法之间的区别,但我已经添加了属性。这可能是什么原因造成的,我怎样才能让它再次工作?

【问题讨论】:

  • 尝试清理并重建项目。
  • 您需要为重载添加属性或为接受动词添加属性,请参阅stackoverflow.com/questions/436866/…
  • 这段代码看起来不错 - 您确定在添加 http 属性后收到该错误吗?
  • 您能否详细说明您是如何“尝试访问创建操作”的?
  • 如果有,你能检查一下 HttpGetAttribute 和 HttpPostAttribute 是从哪个程序集引用的吗?应该是 System.Web.Mvc v4

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


【解决方案1】:

MVC 没有授权你拥有 2 个同名的动作方法。

但是当 http 动词不同(GET、POST)时,您可以有 2 个具有相同 URI 的操作方法。使用 ActionName 属性设置操作名称。不要使用相同的方法名称。您可以使用任何名称。一个约定是添加 http 动词作为方法后缀。

[HttpPost]
[ActionName("Create")]
public ActionResult CreatePost(Customer cust)
{
    if (ModelState.IsValid)
    {
        _repository.Add(cust);
        return RedirectToAction("GetAllCustomers");
    }

    return View(cust);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多