Search code examples
asp.net-core-webapiangular4-httpclient

415 (Unsupported Media Type) angular 4 Post


I am trying to access a wep api with angular 4 post method.

In my service, I've added content-type of application/json. And I'm converting the object into json while sending data to api. I am using HttpClientModule

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()

export class NewServiceService {

  baseUrl = "http://localhost:33969/api/";
  headers = { headers: new Headers({ 'Content-Type': 'application/json' }) 
      };
  obj= {
    name:"A",
    cgpa: 3
  };

_http:any;
constructor(http: HttpClient) {
    this._http = http;
}

SaveStudents(){

    this._http
    .post(
        this.baseUrl + 'home/Save', 
        JSON.stringify(this.obj),
        this.headers
     )
  .subscribe(
    res => {
      alert("Student Saved!");
    },
    err => {
      alert("Error!");
    }
  );
}}

In the API,

using Entity;
using Microsoft.AspNetCore.Mvc;
using Repo;

namespace API_Core.Controllers
{
[Produces("application/json")]
[Route("api/[controller]/[action]")]

public class HomeController : Controller
{
    IStudent _student;
    public HomeController(IStudent student)
    {
        _student = student;
    }

    [HttpPost]   
    public Student Save([FromBody]Student s)
    {
        return _student.Save(s);
    }
}
}

here, I want to catch the objtect as Student model and do something with the data. Here is the Student Model

public class Student
{
    [Key]
    public int ID { get; set; }

    public string Name { get; set; }

    public double Cgpa { get; set; }
}

But when using prostman, I could succesfully receive the object.enter image description here

UPDATE using HttpHeaders instead of Headers and CORS solved the issue

Enabling CORS for ASP.NET Core 2 =>

In ConfigureServices:

services.AddCors(options => options.AddPolicy("Cors", builder =>
        {
            builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader();
        }));

In Configure(Above usemvc()):

app.UseCors("Cors");

Solution

  • You need to change the below line

      headers = { headers: new Headers({ 'Content-Type': 'application/json' }) 
          };
    

    to

    headers={
        headers: new HttpHeaders({
            'Content-Type': 'application/json'
        })
    }