Home > Enterprise >  Posting Json object to ASP net core API
Posting Json object to ASP net core API

Time:04-15

I'm posting a Json object to my ASP net core API and the object looks as following. enter image description here

How do I receive it in the backend so I can access each of the key value pairs?

I cant find a specific response to this question that is not over 4 years old anywhere.

CodePudding user response:

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.

  • Related