I'm trying to consume a JSON file that has the following format as an example in C# API Post. NB:The only way I can consume the file is by using string parameter, because the file is not enclosed in [] brackets nor does it have "," after each row.
Json File
{"id": "1","name": "Cindy","role": [{"name": "HR"}]}
{"id": "2","name": "Frank","role": [{"name": "Admin"}]}
{"id": "3","name": "John","role": [{"name": "Admin"},{"name": "HR"}]}
Code
public async Task<HttpResponseMessage> PostString([FromBody] string _inputJson)
{
if (_inputJson == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NoContent, "The Json was null");
}
else
{
try
{
var arrJson = processJson(_inputJson);
using (ModelEntities entities = new ModelEntities())
{
for (int i = 0; i < arrJson.Count; i++)
{
var jTest = JsonConvert.DeserializeObject<TestClass>(arrJson[i].ToString());
var userRoles = jTest.RolesClass;
var userId = jTest.Id;
entities.User.Add(jTest);
entities.SaveChanges();
foreach (var _role in userRoles)
{
if (_role != null)
{
_role.id = userId;
entities.userRoles.Add(_role);
entities.SaveChanges();
}
}
}
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message.ToString());
}
}
}
public List<string> processJson(string strInput)
{
List<string> arrJson;
return arrJson = strInput.Split('\n').ToList(); //I think the issue is here
}
When I use POST with text/plain, the code runs successfully and inserts the file into SQL, but when using application/JSON to be compliant with the remote server's Posting, I get a 204 code and no data is inserted into SQL.
I also enabled tracing in IIS but somehow it's not logging it, but the 'normal' IIS logs work as below