locked
[FromBody] Attribute in net core 3 not working as expected RRS feed

  • Question

  • User-835909315 posted

    Hi have been starting with a project and i have been stucked with this issue. For some reason net core is not able to parse the incoming request body object into a class model instance. If I use the object generic type i can access the request body but i am losing the validation resources offered by net core plus i must some how make a type casting to store this object in the DB. any help would be appreciate it. It is a big messy to make this manually i think. 

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Text.Json;
    using System.Threading.Tasks;
    
    namespace BuyWhatYouWant.Controllers
    {
      [ApiController]
      [Route("product")]
      public class ProductControlller : Controller
      {
        ILogger _logger;
        public ProductControlller(ILogger<ProductControlller> logger)
        {
          _logger = logger;
        }
        [HttpGet]
        [Route("")]
        public string Get() => "This should be your first request";
    [HttpPost] [Route("add")] public IActionResult Add([FromBody] Product p) /// <------------ HERE IS THE PROBLEM. Like this i get an empty object in postman {} => Json(p);
    /*
    [HttpPost]
    [Route("add")]
    public IActionResult Add([FromBody] object p) /// <------------ Like this i get the expected result; =>Json(p);
    */ } public class Product { public string Name; public string Type; } }
    Friday, December 13, 2019 11:07 PM

Answers

  • User475983607 posted

    Use properties not fields.

        public class Product
        {
            public string Name { get; set; }
            public string Type { get; set; }
        }

    If you are still having issues after making this change, share the client source code.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, December 14, 2019 12:02 AM

All replies

  • User475983607 posted

    Use properties not fields.

        public class Product
        {
            public string Name { get; set; }
            public string Type { get; set; }
        }

    If you are still having issues after making this change, share the client source code.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, December 14, 2019 12:02 AM
  • User-835909315 posted

    It worked. Thanks. I didn't see that detail. surprised . Thanks

    Saturday, December 14, 2019 11:20 AM