SP Tutorials
SP Tutorials

Reputation: 25

Action method overrides for HTTPPost .net core

I have two Post method one is taking single object and one is taking list of object, how to do this overriding in .net core?

// taking list of object
[HttpPost("matchdob")]
public MatchDOBResponse MatchDOB(List<DOBMatchRequest> requestModel)
{
  //
}
// taking single object
[HttpPost("matchdob")]
public MatchDOBResponse MatchDOB(DOBMatchRequest requestModel)
{
  //
}

its not working, how to solve this issue?

Upvotes: 0

Views: 706

Answers (2)

Victor
Victor

Reputation: 8890

Actually it is possible to implement what you are asking. It is necessary to use the route constraints.

For example, the following two action method will be called with the same action name Method depend on the data parameter type: the first when data is int, and the second when the data parameter is bool.

[HttpPost, Route("{data:int}")]        
public IActionResult Method(int data)
{
    return RedirectToAction("Method1", data);
}

[HttpPost, Route("{data:bool}")]        
public IActionResult Method(bool data)
{
    return RedirectToAction("Method2", data);
}

In your case the Custom route constraints should be implemented to use this feature: one class to support DOBMatchRequest type, and the second class for List<DOBMatchRequest> type.

For more information see:

Route constraints

Custom route constraints

Note: Yes... this is more likely overloading, not overriding.

Upvotes: 0

Zhi Lv
Zhi Lv

Reputation: 21353

You can't set the multiple action with the same template name. Each action should have a unique route name.

Try use different name, like this:

// taking list of object
[HttpPost("matchdmultipleob")]
public MatchDOBResponse MatchDOB(List<DOBMatchRequest> requestModel)
{
  //
}
// taking single object
[HttpPost("matchdsingleob")]
public MatchDOBResponse MatchDOB(DOBMatchRequest requestModel)
{
  //
}

Or you can use one action method and receive a list of object, then check the count:

[HttpPost("matchdob")]
public MatchDOBResponse MatchDOB(List<DOBMatchRequest> requestModel)
{
    if (requestModel.Count == 1)
    {
        //upload single object
        //do something
    }
    else
    {
        //upload list of object
    }

    //
    return new MatchDOBResponse() { Status = "200", Message = "Success" };
}

Upvotes: 1

Related Questions