Search code examples
jsonangularapihttp-post.net-5

.Net5 backend receives empty JSON


I implemented a simple server with .Net5 and an Angular frontend. My api works with post man but only if I set Content-Type equal to application/x-www-form-urlencoded. When I use Content-Type equal to application/json the server receives empty json. When I use my frontend I think I send to server an application/json because it receives the empty one. Below my code.

api.service.ts

    public createProva(prova:Iprova): Observable<Iprova> {
        return this.http.post<Iprova>( this.Url, prova );
    }

When I console.log prova it return a correct Json

controller.cs

        [HttpPost]
        [Route("url")]
        public async Task<IActionResult> postProva(provaDto s)
        {
            porvaModel prova = new provaModel
            {
                Id = s.id,
                Name = s.name
            };

            _context.provaModel.Add(prova);
            await _context.SaveChangesAsync();
            return CreatedAtAction(nameof(getProva), new { id = prova.Id }, prova);
        }

but when backend receives provaDto, s is empty with id equal to 0 and name equal to null.


Solution

  • For simplicity, I assume you have a basic setup for your controller such as this :

    [ApiController]
    [Route("[controller]")]
    public class ProvaController : ControllerBase
    

    I also disable the https redirection in the startup.cs for development purposes, while keeping the default routing functionality.

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {     
            if (!env.IsDevelopment())
            {
                app.UseHttpsRedirection();
            }
    
            app.UseRouting();            
    
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    

    I'll keep the same post method:

        [HttpPost]
        
        public async Task<IActionResult> postProva(provaDto s)
        {
            porvaModel prova = new provaModel
            {
                Id = s.id,
                Name = s.name
            };
    
            _context.provaModel.Add(prova);
            await _context.SaveChangesAsync();
            return CreatedAtAction(nameof(getProva), new { id = prova.Id }, prova);
        }
    

    As for the Postman setup, I use a POST request on http://localhost:5000/Prova (I use the default launchSettings using dotnet CLI), I also keep default headers. In the Body, I'll use raw and select JSON format, giving it a simple payload :

    {
    "id": 0,
    "name": "string"
    }
    

    As for the angular part, you can specify the content-type of your resquest with the httpOptions :

    httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
      })
    };
    public createProva(prova:Iprova): Observable<Iprova> {
        return this.http.post<Iprova>( this.Url, prova , this.httpOptions);
    }