1

I have a problem with my web api developed in asp.net core. When I call them in POST I get the following error:

ebbtelemetrywebapi.azurewebsites.net/api/events:1 Failed to load resource: >the server responded with a status of 500 (Internal Server Error)

The controller function il the following :

    [Route("api/[controller]")]
    [ApiController]
    public class EventsController : ControllerBase
    {
      [HttpPost]
      public async Task<IEnumerable<CosmosDBEvents>> 
      GetAsync(EventsGetTwoParamsDto dto)
      {
         try
            {
                switch(dto.Action2)
                {
                    case "Index":
                    case "Pagina5":
                        const string VERIFICATION_CODE = "where doc.deviceId = \"{0}\"";
                        var content = string.Format(VERIFICATION_CODE,dto.DeviceIdorId);

                        var items = await DocumentDBRepository<CosmosDBEvents>.GetItemsAsync(content);

                        if (items == null || items.Count() == 0)
                        {
                            return null;
                        }
                        MessagesController messageController = new MessagesController(_context);
                        EventsTypeDescriptionsController eventController = new EventsTypeDescriptionsController(_context);

                        int codice_evento;
                        string cultura;

                        foreach (var item in items)
                        {
                            codice_evento = Convert.ToInt32(item.eventId);
                            cultura = GetCulture();
                            item.decodifica_evento = messageController.GetMessageWithCulture(codice_evento, cultura);
                            item.descrizione_evento = eventController.GetDetail(codice_evento);
                        }
                        return (items);
                    case "BottoneLedOff":
                        content = string.Format(VERIFICATION_CODE, dto.DeviceIdorId);

                        items = await DocumentDBRepository<CosmosDBEvents>.GetItemsAsync(content);

                        if (items == null || items.Count() == 0)
                        {
                            return null;
                        }
                        items = (from item in items
                                 orderby item.startTS descending
                                 select item).Take(1);

                        var service = ServiceClient.CreateFromConnectionString(AppSettings.KeyIoT);
                        var methodInvocation = new CloudToDeviceMethod("GetData") { ResponseTimeout = TimeSpan.FromSeconds(200) };
                        var response = await service.InvokeDeviceMethodAsync(dto.DeviceIdorId, methodInvocation);

                        CosmosDBTelemetry realtime = JsonConvert.DeserializeObject<CosmosDBTelemetry>(response.GetPayloadAsJson());

                        if(realtime.severity<90)
                        {
                            ((List<CosmosDBEvents>)items)[0].BLedAcceso = true;
                        }
                        else
                        {

                            ((List<CosmosDBEvents>)items)[0].BLedAcceso = false;
                        }

                        return (items);
                    case "Dettagli":
                        // in questo caso il deviceid è l'id dell'evento eventId
                        if (dto.DeviceIdorId == null)
                        {
                            return null;
                        }

                        items = await DocumentDBRepository<CosmosDBEvents>.GetItemAsync(dto.DeviceIdorId);
                        var events = items.FirstOrDefault();


                        codice_evento = Convert.ToInt32(events.eventId);
                        cultura = GetCulture();


                        messageController = new MessagesController(_context);
                        events.decodifica_evento = messageController.GetMessageWithCulture(codice_evento, cultura);

                        eventController = new EventsTypeDescriptionsController(_context);
                        events.descrizione_evento = eventController.GetDetail(codice_evento);

                        if (events == null)
                        {
                            return null;
                        }
                        //ritorno una lista di un elemento
                        List<CosmosDBEvents> toRet = new List<CosmosDBEvents>
                        {
                            events
                        };
                        return (toRet);
                    default:
                        return null;
                }
            } catch(Exception ex)
            {
                throw (ex);
            }
        }
   }

The dto class is declared as following :

    public class EventsGetTwoParamsDto
    {
        public string DeviceIdorId { get; set; }
        public string Action2 { get; set; }
    }

The AJAX call is the following :

     $.ajax({
        type:"POST",
        url: ENV.apiUrl+'/events',
        data: JSON.stringify({ DeviceIdorId: ENV.deviceId, Action2: 
    "Pagina5"}),
        dataType: "json",
        contentType: 'application/json;charset=UTF-8',
        success: function(data){
            console.log("RISPOSTA", data);
        }
      });

I got the following exception :

Microsoft.AspNetCore.Mvc.Internal.AmbiguousActionException: Multiple actions matched. The following actions matched route data and had all constraints satisfied:

I take a look to AmbiguousActionException: Multiple actions matched. The following actions matched route data and had all constraints satisfied but my case is a bit different. In my controller I have two GetAsync methods one that takes two parameters and one that takes three parameters. I believe this is the origin of the problem. In the post you mentioned you there is no such case and above all the case of POST methods.

Here it is the controller class:

[Route("api/[controller]")]
[ApiController]
public class EventsController : ControllerBase
{

    private readonly TelemetryWebContext _context;

    public EventsController(TelemetryWebContext context)
    {
        _context = context;
    }

    [HttpPost]
    public async Task<IEnumerable<CosmosDBEvents>> GetAsync([FromBody]EventsGetTwoParamsDto dto)
    {
    }

    [HttpPost]
    public async Task<IEnumerable<CosmosDBEvents>> GetAsync([FromBody]EventsGetThreeParamsDto dto)
    {
    }

    private string GetCulture() => "en-GB";
  }

Can sameone help me?

Simone Spagna
  • 626
  • 7
  • 27

1 Answers1

1

I solved the problem giving to the second method of the controller a new URL segment by using the HttpPost overload.

For example

[HttpPost("xyz")]

I thank CodeNotFound for the help he gave me.

CodeNotFound
  • 22,153
  • 10
  • 68
  • 69
Simone Spagna
  • 626
  • 7
  • 27