-1

I designe a request which will accept all the types of inputs like XML, JSON, etc.
Accordingly the method will respond and will give the corresponding output.
Is there any example on that?

I have tried the below code.
When I call it from Postman it is giving a

415 ERROR.

[HttpPost("/GetOutput", Name = nameof(GetOutput))]
[Consumes("application/xml","application/json", "text/plain")]        
public IActionResult GetOutput(dynamic request)
{
    //process         
    return new ObjectResult(res.ToString());
}
jps
  • 20,041
  • 15
  • 75
  • 79
Shraddha
  • 115
  • 2
  • 11

1 Answers1

0

Allowing a user to submit all the types of input can be a super-dangerous idea. You never know what your users will submit.

If you just want to accept a text-based input, like what your example is trying to do , accepting json/xml/text, you can try this:

1. Define a binding model. No dynamic:

public class MyRequestBindingModel
{
    // the type of Content.
    public string Type { get; set; }

    // the serialized json/xml/text content.
    public string Content { get; set; }
}

2. Your controller action:

[HttpPost("/GetOutput")]
public IActionResult GetOutput([FromBody] MyRequestBindingModel request)
{
    // process
    switch(request.Type.ToLower())
    {
        case "json": _processJsonInput(request.Content); 
        case "xml": _processXmlInput(request.Content); 
        default: _processTextInput(request.Content); 
    }

    // do something else you want
}

The switch statement in the above example is just showing an idea on how to handle the string content base on the Type provided.

If you want to return XML if the Content in the API call is XML, this answer may be helpful:
Helpful Answer.

LopDev
  • 823
  • 10
  • 26
Bemn
  • 1,291
  • 1
  • 7
  • 22