Program Tip

동일한 컨트롤러에서 동일한 작업 이름을 가진 GET 및 POST 메서드

programtip 2020. 10. 15. 21:28
반응형

동일한 컨트롤러에서 동일한 작업 이름을 가진 GET 및 POST 메서드


이것이 잘못된 이유는 무엇입니까?

{
    public class HomeController : Controller
    {

        [HttpGet]
        public ActionResult Index()
        {
            Some Code--Some Code---Some Code
            return View();
        }

        [HttpPost]
        public ActionResult Index()
        {
            Some Code--Some Code---Some Code
            return View();
        }

    }

제어자가 "얻었을 때"와 "게시"할 때 한 가지에 어떻게 대답하도록 할 수 있습니까?


동일한 이름과 서명을 가진 두 가지 메소드를 가질 수 없으므로 ActionName속성 을 사용해야 합니다.

[HttpGet]
public ActionResult Index()
{
  // your code
  return View();
}

[HttpPost]
[ActionName("Index")]
public ActionResult IndexPost()
{
  // your code
  return View();
}

"메소드가 작업이되는 방법" 도 참조하십시오.


ASP.NET MVC를 사용하면 이름이 같은 두 가지 작업을 사용할 수 있지만 .NET에서는 서명이 같은 두 메서드 (즉, 이름과 매개 변수가 같은)를 사용할 수 없습니다.

메서드 이름을 다르게 지정해야합니다. ActionName 특성을 사용하여 ASP.NET MVC에 실제로 동일한 작업임을 알립니다.

즉, GET 및 POST에 대해 이야기하는 경우 POST 작업이 GET보다 더 많은 매개 변수를 사용하므로 구별이 가능하므로이 문제는 사라질 가능성이 높습니다.

따라서 다음 중 하나가 필요합니다.

[HttpGet]
public ActionResult ActionName() {...}

[HttpPost, ActionName("ActionName")]
public ActionResult ActionNamePost() {...}

또는,

[HttpGet]
public ActionResult ActionName() {...}

[HttpPost]
public ActionResult ActionName(string aParameter) {...}

필요하지 않더라도 내 POST 작업에 대한 양식 게시물을 수락하고 싶습니다. 나에게 그것은 당신이 뭔가를 게시하는 것처럼 옳은 일처럼 느껴집니다 .

public class HomeController : Controller
{
    public ActionResult Index()
    {
        //Code...
        return View();
    }

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

특정 질문에 답하기 위해 단일 클래스에서 동일한 이름과 동일한 인수를 가진 두 개의 메서드를 가질 수 없습니다. HttpGet 및 HttpPost 특성을 사용하는 것은 메서드를 구분하지 않습니다.

이 문제를 해결하기 위해 일반적으로 게시중인 양식에 대한보기 모델을 포함합니다.

public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        Some Code--Some Code---Some Code
        return View();
    }

    [HttpPost]
    public ActionResult Index(formViewModel model)
    {
        do work on model --
        return View();
    }

}

동일한 이름과 동일한 매개 변수를 다중 작업 할 수 없습니다.

    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public ActionResult Index(int id)
    {
        return View();
    }

비록 int id는 사용되지 않지만


You can't have multiple actions with the same name. You could add a parameter to one method and that would be valid. For example:

    public ActionResult Index(int i)
    {
        Some Code--Some Code---Some Code
        return View();
    }

There are a few ways to do to have actions that differ only by request verb. My favorite and, I think, the easiest to implement is to use the AttributeRouting package. Once installed simply add an attribute to your method as follows:

  [GET("Resources")]
  public ActionResult Index()
  {
      return View();
  }

  [POST("Resources")]
  public ActionResult Create()
  {
      return RedirectToAction("Index");
  }

In the above example the methods have different names but the action name in both cases is "Resources". The only difference is the request verb.

The package can be installed using NuGet like this:

PM> Install-Package AttributeRouting

If you don't want the dependency on the AttributeRouting packages you could do this by writing a custom action selector attribute.


You received the good answer to this question, but I want to add my two cents. You could use one method and process requests according to request type:

public ActionResult Index()
{
    if("GET"==this.HttpContext.Request.RequestType)
    {
        Some Code--Some Code---Some Code for GET
    }
    else if("POST"==this.HttpContext.Request.RequestType)
    {
        Some Code--Some Code---Some Code for POST
    }
    else
    {
        //exception
    }

    return View();
}

Today I was checking some resources about the same question and I got an example very interesting.

It is possible to call the same method by GET and POST protocol, but you need to overload the parameters like that:

@using (Ajax.BeginForm("Index", "MyController", ajaxOptions, new { @id = "form-consulta" }))
{
//code
}

The action:

[ActionName("Index")]
public async Task<ActionResult> IndexAsync(MyModel model)
{
//code
}

By default a method without explicit protocol is GET, but in that case there is a declared parameter which allows the method works like a POST.

When GET is executed the parameter does not matter, but when POST is executed the parameter is required on your request.

참고URL : https://stackoverflow.com/questions/9552761/get-and-post-methods-with-the-same-action-name-in-the-same-controller

반응형