Click here to Skip to main content
15,879,613 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I am receiving multiple json objects from datasource like this:

[{"SerialNumber":1,"LabParameterName":"Hemoglobin","LabValue":7.80},{"SerialNumber":2,"LabParameterName":"ESR","LabValue":10.00},{"SerialNumber":3,"LabParameterName":"Total WBC Count","LabValue":5.00},{"SerialNumber":18,"LabParameterName":"Neutrophils","LabValue":200.0}]

I want to post this in web api...

What I have tried:

public class ApiSender
    {
        private static HttpClient _httpClient = new HttpClient();
        public bool POSTData(object json, string url)
        {
            _httpClient.DefaultRequestHeaders.Accept.Clear();
            string abc = JsonConvert.SerializeObject(json);
            using (var content = new StringContent(abc, Encoding.UTF8, "application/json"))
            {
                HttpResponseMessage result = _httpClient.PostAsJsonAsync(url, content).Result;
                if (result.StatusCode == System.Net.HttpStatusCode.Created)
                    return true;
                string returnValue = result.Content.ReadAsStringAsync().Result;
                throw new Exception($"Failed to POST data: ({result.StatusCode}): {returnValue}");
            }
        }
    }


I am getting this error:

{StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Date: Tue, 27 Sep 2022 20:24:44 GMT
Server: Kestrel
Transfer-Encoding: chunked
Content-Type: application/problem+json; charset=utf-8
}}

[Route("api/[controller]")]
    [ApiController]
    public class LabDataController : ControllerBase
    {
        private readonly LabDbContext _context;

        public LabDataController(LabDbContext context)
        {
            _context = context;
        }

        // GET: api/LabData
        [HttpGet]
        public async Task<ActionResult<IEnumerable<LabDatas>>> GetLabDatas()
        {
            return await _context.LabDatas.ToListAsync();
        }

        // GET: api/LabData/5
        [HttpGet("{id}")]
        public async Task<ActionResult<LabDatas>> GetLabDatas(int id)
        {
            var labDatas = await _context.LabDatas.FindAsync(id);

            if (labDatas == null)
            {
                return NotFound();
            }

            return labDatas;
        }

        // PUT: api/LabData/5
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPut("{id}")]
        public async Task<IActionResult> PutLabDatas(int id, LabDatas labDatas)
        {
            if (id != labDatas.Id)
            {
                return BadRequest();
            }

            _context.Entry(labDatas).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!LabDatasExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/LabData
        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
        [HttpPost]
        public async Task<ActionResult<LabDatas>> PostLabDatas(LabDatas labDatas)
        {
            _context.LabDatas.Add(labDatas);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetLabDatas", new { id = labDatas.Id }, labDatas);
        }

        // DELETE: api/LabData/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteLabDatas(int id)
        {
            var labDatas = await _context.LabDatas.FindAsync(id);
            if (labDatas == null)
            {
                return NotFound();
            }

            _context.LabDatas.Remove(labDatas);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool LabDatasExists(int id)
        {
            return _context.LabDatas.Any(e => e.Id == id);
        }
    }


public class LabData
    {
        public int Id { get; set; }
        public int SerialNumber { get; set; }
        public string LabParameterName { get; set; }
        public decimal LabValue { get; set; }
        public DateTime LabDate { get; set; }
    }
Posted
Updated 27-Sep-22 10:27am
v3

1 solution

The incoming parameter is incorrect.

[{"SerialNumber":1,"LabParameterName":"Hemoglobin","LabValue":7.80},{"SerialNumber":2,"LabParameterName":"ESR","LabValue":10.00},{"SerialNumber":3,"LabParameterName":"Total WBC Count","LabValue":5.00},{"SerialNumber":18,"LabParameterName":"Neutrophils","LabValue":200.0}]


Simply create a new class (new file to hold the class) which looks like the following:

C#
public class LabData{
    public int SerialNumber {get;set;}
    public String LabParameterName {get;set;}
    public float LabValue {get;set;}
}


Note: Each property that we add MUST match the names in the JSON exactly.

After that, change your incoming parameter so it looks like the following:


C#
public bool POSTData(List<LabData> inLabData, string url)
{
   ...
   // use the object as you expect down in here
   // Console.WriteLine(inLabData[0].SerialNumber);
   ...


I'm not sure why I don't really see your Controller but you'll have to work that out yourself.
I'm assuming this WebAPI is created in C# .NET Web API.
 
Share this answer
 
Comments
SaeefAlDeen 27-Sep-22 16:18pm    
PostData incoming parameter (object json) receiving json object from datasource, i am trying to send those objects in webapi...
so i convert json object to string
"[{\"SerialNumber\":1,\"LabParameterName\":\"Hemoglobin\",\"LabValue\":7.80},{\"SerialNumber\":2,\"LabParameterName\":\"ESR\",\"LabValue\":10.00},{\"SerialNumber\":3,\"LabParameterName\":\"Total WBC Count\",\"LabValue\":5.00},{\"SerialNumber\":18,\"LabParameterName\":\"Neutrophils\",\"LabValue\":200.0}]"
then trying to send using
_httpClient.PostAsJsonAsync(url, content).Result;
but it is not calling HttpPost method and returning 400 bad request

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900