bdotnet
bdotnet

Reputation: 353

Asp.Net Core - multiple action methods with the same name and different parameters

I'm looking for a way to have more than one action method with the same name in controller without changing Url (route).

[HTTPPost]
Public ActionResult Method1 (Dto1 param)
{
}

[HTTPPost]
Public ActionResult Method2 (Dto2 param)
{
}

[HTTPPost]
Public ActionResult Method3 (Dto3 param)
{
}

This throws error -

Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpoints

Dto1, Dto2 and Dto3 derive from a base Dto, each have properties specific to different request methods. I am trying to avoid having a single method with a common Dto which will require multiple validations such as validating mandatory fields based on the value of other fields, etc. If we can have 3 different Post methods with different Dtos, it would makes things much easier

Adding Dtos (Simplified)

public class BaseDto
{
    public string CommonProp1 { get; set; }
    public string CommonProp2 { get; set; }
}

public class Dto1: BaseDto
{
    public enumType Type = enumType.Type1;
    public string Property1 { get; set; }
}

public class Dto2 : BaseDto
{
    public enumType Type = enumType.Type2;
    public string Property2 { get; set; }
}

public class Dto3 : BaseDto
{
    public enumType Type = enumType.Type3;
    public string Property3 { get; set; }
}

Upvotes: 1

Views: 2527

Answers (1)

Leandro Bardelli
Leandro Bardelli

Reputation: 11588

You can use Routes or calling a private method from the three above methods, you shouldn't do this as you want. I think your problem is more deep.

But.... if you still want it, here is a workaround.

Instead of receiving an object, receive a string with json content and parse the object.

But you will have to have a property inside the "json object" or another parameter that defines you wich object it is (Dto1, Dto2 or Dto3). In any case will be the same that use different routes or methods because objects are different.

[HTTPPost]

Public ActionResult Method (string param)
{

//Decode your string called param with JSON with a property inside

}

or

[HTTPPost]
Public ActionResult Method (string param, int type)
{

//Decode your string called param with JSON switching "type" as 1, 2 or 3

}

UPDATE after your update:

I suggest you receive BaseDto and the type in other parameter.

[HTTPPost]
Public ActionResult Method (BaseDto param, int type)
{
 

}

Upvotes: 1

Related Questions