'Posting Json object to ASP net core API
Solution 1:[1]
It depends on what you use on the backend side: I assume here that you are using MVC and therefore have endpoints.
When posting JSON to a C# endpoint you most likely need to create a C# model for that.
The JavaScript model you send:
{
productNumber: 'TEST',
allowedRStates: 'Allowed *',
productType: 'Type 1',
enableMachineLearningService: false,
productFamilyId: 1,
parentProductId: null,
addedDate: '2021-04-26 10:09:16.164',
modifiedDate: '2021-04-27 19:19:53.112',
productGuid: '345',
comPortAlias: 'RadioCool',
hwsEnableLogAnalysis: false
}
Could be modeled by a C# class like so:
namespace XYZ
{
using System;
using System.Linq;
public class SampleModel
{
#region properties
public string ProductNumber { get; set; }
public string AllowedRStates { get; set; }
public string ProductType { get; set; }
public bool EnableMachineLearningService { get; set; }
public long ProductFamilyId { get; set; }
public long ParentProductId { get; set; }
public DateTimeOffset AddedDate { get; set; }
public DateTimeOffset ModifiedDate { get; set; }
public string ProductGuid { get; set; }
public string ComPortAlias { get; set; }
public bool HwsEnableLogAnalysis { get; set; }
#endregion
}
}
In your C# controller class you can now create a new endpoint for your post request:
...
[HttpPost("PostTest")]
public async Task<IActionResult> PostTest([FromBody] SampleModel model)
{
// Start to use your send data as 'model' from here on.
return Ok();
}
...
When you now create a fetch request in JavaScript for this new endpoint, C# will parse the POST Body JSON into the new C# model. From this moment on you can use your send data on the C# side like any other normal C# model.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | R0B1N |

