Following is my Json input from Ui:
{
"data": [{
"Id": 1
}, {
"Id": 2
}, {
"Id": 3
}]
}
I can receive it without an issue in the object structure shown below:
public class TestController : ApiController
{
/// <summary>
/// Http Get call to get the Terminal Business Entity Wrapper
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost]
[Route("api/TestJsonInput")]
public string TestJsonInput([FromBody] TestInput input)
{
return JsonConvert.SerializeObject(input.data);
}
public class TestInput
{
public List<Info> data { get; set; }
}
public class Info
{
public int Id { get; set; }
}
}
However my objective is to receive in following API method:
[HttpPost]
[Route("api/TestJsonInput")]
public string TestJsonInput1([FromBody] string input)
{
return input;
}
Reason for this requirement is, I have no use of the Json object de-serialized via Web API, I just need to persist the actual Json to the Database and fetch and return to Ui, which will parse it back.
As I am not able to receive in the string input as suggested, so I have to carry out extra step of Json serialization, de-serialization to achieve the objective. Any mechanism for me to avoid this workaround totally by receiving in a string and using it directly. I am currently testing using Postman
If your web API receives loosely structured JSON objects from clients, you can deserialize the request body to a Newtonsoft.Json.Linq.JObject type. However, it is usually better to use strongly typed data objects. Then you don't need to parse the data yourself, and you get the benefits of model validation.
The JSON will be deserialized using NewtonSoft.Json library in ASP.Net Core. Note: For beginners in ASP.Net MVC Core, please refer my article ASP.Net MVC Core Hello World Tutorial with Sample Program example.
May i know how to receive the Json string in api. Normally, in cases when you need to send JSON, you should make POST/PUT request and send JSON in the request body.
But when you try to pass an entire JSON structure in as part of the makeup of the URL, you break REST. You really want to send a POST request, and have the JSON be that body of that request. @BrandonMiller I will try with remove one bracket. May i know how to receive the Json string in api.
You can read the body content directly as a string regardless of what you put in the parameters of your method. You dont actually need to put anything in the parameters and you can still read the body.
[HttpPost]
[Route("api/TestJsonInput")]
public string TestJsonInput1()
{
string JsonContent = Request.Content.ReadAsStringAsync().Result;
return JsonContent;
}
You dont need to read the input as a parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With