0

I am trying to get my WebAPI POST method to take ANY possible properly formatted Json as input.

For now, what I do is something like this:

[HttpPost("import")]
public IActionResult Import ([FromBody] Request exampleRequest)
{
  //...
}

Where the Request class is structured like this:

public class Request
{
  public string Json { get; set; }
}

So I have to put something like this into the body of the POST request:

{
    "json": "example_Json_in_string_form"
}

So what I do now is I ask for a Json containing a field called "Json" where I put the Json in string form. This method works fine, but I'd prefer a way to directly put the Json in non string form into the POST request.

The reason I didn't create a Model containing the fields of a Json is because I want to be able to take in any properly formatted Json, so that way is off limits (unless I'm missing something).

Is there a way to do what I want to do or am I forced to use the method I'm currently using?

1 Answers1

0

One way to solve this problem that I can think of is send the entire body as a string. So now your request looks a bit like this

[HttpPost("import")]
public IActionResult Import ([FromBody] string request)
{
  //...
}

Then you have a few options

  1. You validate the input as JSON using a JSON validator. You can use JSON.NET or take a look at this SO post to help - How to make sure that string is valid JSON using JSON.NET
  2. You can simply pass the string along to other functions. I'd never recommend this for the mere fact that passing it along with sanitization/validation could lead to just bad data finding its way like an inject attack but if its an internal system then it should be okay.

If the validation fails, just return the error to the caller and if it passes you now have a properly formed JSON object in string format to manipulate any way you need.

Melroy Coelho
  • 212
  • 2
  • 6
  • Is there a way to do this without a string? I want to be able to copy a bunch of Json text and paste it into the body of a Post request without first having to convert the Json text into string form. – Librapulpfiction Aug 10 '23 at 06:37
  • From my perspective you want it to be in a format you can easily traverse and parse for ease of usage so I went with string and I think that might really be your best bet here. It's easy to validate bad data without the parser too if you want to write your own analyzer, etc. – Melroy Coelho Aug 11 '23 at 05:09