Ahad Porkar
Ahad Porkar

Reputation: 1698

ASP.NET Core MVC 1.0 multiple post method in one Controller

I can do this by using this code :

    [HttpPost("SampleRoute1")]
    public JsonResult Post([FromBody]SampleModel1 value)
    {
        .....Functionone.....
        return Json("");
    }

    [HttpPost("SampleRoute2")]
    public JsonResult Post([FromBody]SampleModel2 value)
    {
        .....Functiontwo.....
        return Json("");
    }

but i cant do this :

    [HttpPost("SampleRoute1")]
    public JsonResult Post([FromBody]SampleModel1 value)
    {
        .....Functionone.....
        return Json("");
    }

    [HttpPost("SampleRoute2")]
    public JsonResult Post([FromBody]SampleModel1 value)
    {
        .....Functiontwo.....
        return Json("");
    }

it gives error "Type 'Controller1' already defines a member called 'Post' with the same parameter types"

so is there any way that i can make two Post in one controller with same paramter but with different route?

like this :

Posting(SampleModel1) => "Controller1\SampleRoute1" => Doing Function1

Posting(SampleModel1) => "Controller1\SampleRoute2" => Doing Function2

Upvotes: 2

Views: 4849

Answers (2)

Brendan Vogt
Brendan Vogt

Reputation: 26018

You are getting the error because you have 2 methods that are identical. How would you know which one to execute? Are you basing this on the routes that you defined?

If I gave you 2 identical red apples to eat, there is no difference between the 2 apples, and I told you to eat the correct apple, would you know which is the correct apple?

You are going to have to change your method names so that they are unique and identifiable.

[HttpPost("SampleRoute1")]
public ActionResult Function1(SampleModel1 model)
{
     return Json("");
}

[HttpPost("SampleRoute2")]
public ActionResult Function2(SampleModel1 model)
{
     return Json("");
}

So based on the above, the following will happen:

  • So now when posting SampleModel1, using route Controller1\SampleRoute1 will execute action method Function1
  • So now when posting SampleModel2, using route Controller1\SampleRoute2 will execute action method Function2.

Upvotes: 3

Martin Vich
Martin Vich

Reputation: 1082

Yes, you can do that. Problem is that you're trying to have two methods in a class that have same name & parameters and that's not possible. You should change name of your methods to something different.

Note that the action name & Post request type are already specified in the HttpPost attribute so you don't have to rely on the method name.

[HttpPost("SampleRoute1")]
public JsonResult Aaa([FromBody]SampleModel1 value)
{
    .....Functionone.....
    return Json("");
}

[HttpPost("SampleRoute2")]
public JsonResult Bbb([FromBody]SampleModel1 value)
{
    .....Functiontwo.....
    return Json("");
}

Upvotes: 8

Related Questions