415 (Unsupported Media Type) angular 4 Post
Asked Answered
D

3

10

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");
Desolate answered 9/4, 2018 at 5:50 Comment(3)
Saved my life with this edited answer! THXChristabella
Where do we find ConfigureServices and Configure in startup class ? Can you show how to add thoseBaecher
@SujayUN those are methods that are created when the project is created go ahead a search inside the Startup.cs file and you will find themFamous
S
13

You need to change the below line

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

to

headers={
    headers: new HttpHeaders({
        'Content-Type': 'application/json'
    })
}
Schoolbook answered 9/4, 2018 at 6:6 Comment(4)
after changing that line. It throws a new error "OPTIONS localhost:33969/api/home/Save net::ERR_CONNECTION_RESET"Desolate
Is your Angular app and the API hosted on different port? if yes, may be you need to enable CORS.Schoolbook
Yes. I've enabled Cors. I could successfully send a get request to the api and received proper data. But when i'm trying to do post, I'm facing problemDesolate
Can you post the request payload that is going out from the angular client? with Dev tools, or fiddler.Schoolbook
F
6

In my case the 415 error was caused because I was calling JSON.stringify(obj) when there was no need for it. I read somewhere that post method will stringify the body parameter as needed

So instead of this:

this._http
.post(
    this.baseUrl + 'home/Save', 
    JSON.stringify(this.obj),
    this.headers
 )

I changed it to this:

this._http
.post(
    this.baseUrl + 'home/Save', 
    this.obj, // << no need to stringify 
    this.headers
)

Here is my actual working code

@Injectable()
export class ParkingService {
  constructor(private http: HttpClient) { }

  create(parking: Parking) {
    const requestUrl = environment.apiUrl + 'parking' ;
    const headerOptions = new HttpHeaders();

    headerOptions.set('Content-Type', 'application/json');
    return this.http.post(requestUrl, parking, {headers: headerOptions}) ;
  }
}

This happened to me even after enabling and configuring CORS on the .NET core web api

Famous answered 9/6, 2019 at 13:12 Comment(2)
thanks buddy.. this one really helped meUndercoating
unbelievable! this worksChervonets
A
1

I had the same problem using angular 6 with .netcore 2. My code was this:

Angular:

  getCustomers(pageSize: number, pageNumber: number) {

    let fromObject = {
      name: this.searchName,
      pageNumber: pageNumber.toString(),
      pageSize: pageSize.toString()
    }

    const params = new HttpParams({
      fromObject: fromObject
    });

    return this.http.get(this.baseUrl, { params: params });

  }

.Net Core

[HttpGet]
public IActionResult GetCustomers(PageSelection page)

The problem was solved with two different ways.

First one:

[HttpGet]
public IActionResult GetCustomers(string Name, int PageSize, int PageNumber)

Second one, although I had added [ApiController]

[HttpGet]
public IActionResult GetCustomers([FromQuery]PageSelection page)

Hope it helps.

Animalcule answered 9/9, 2019 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.