简体   繁体   中英

Post Action method overload with same route name in ASP.Net Web API Controller

Is it possible to have two actions with same route name and same method but different parameter? I have tried this:

[HttpPost]
[Route("gstr4")]
public HttpResponseMessage SubmitGSTR4([FromBody] RequestPayloadWithoutSign requestPayload)
{ }

[HttpPost]
[Route("gstr4")]
public HttpResponseMessage FileGSTR4([FromBody] RequestPayloadWithSign requestPayload)
{ }

I received a Status Code of 500 (InternalServerError) and here is raw response:

{"Message":"An error has occurred.","ExceptionMessage":"Multiple actions were found that match the request: \r\nFileGSTR4 on type APIPortal.Controllers.GSTR4Controller\r\nSubmitGSTR4 on type APIPortal.Controllers.GSTR4Controller","ExceptionType":"System.InvalidOperationException","StackTrace":"   at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)\r\n   at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n   at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"}

It's not possible for the same method type as http Get for multiple methods. You should have a different route

It is only possible with different HTTP verbs. Otherwise, you have to define different routes.

https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

It's not possible to have many actions with the same route and the same HTTP verb.

What you could do is to have a single action which accepts a base class and a custom resolver.

For example:

public abstract class RequestPayload 
{
}

public class RequestPayloadWithoutSign : RequestPayload
{
}

public class RequestPayloadWithSign : RequestPayload
{
   public string Sign { get; set; }
}

And a custom JSON resolver attached to your JSON deserializer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM