Search code examples
c#xmlhttprequestasp.net-core-webapi

Make ASP.Net Core Web API endpoint to consume any data type as payload


I am creating an API endpoint that can receive any kind of data type but I am not sure how to specify that in my method

I currently have the following

 [HttpPost]
 public async Task<IActionResult> Index(string? req = null)
 {
   .......
 }

I want to be able to receive any type of POST request payload because the request comes from different sources in different formats. I can work on the request within the method to convert it to other data types as desired after it has been received

Thank you


Solution

  • To make the endpoint accept any type of input parameter, the following piece of code can do it

     public async Task<IActionResult> Index([FromBody] object? request = null)
     {
      //Other code to validate the request and convert to any desired type of object
      ...
     }
    

    With this, the endpoint can receive any type of object and process it according to the other parts of the code

    I hope this helps someone