415(不支持的媒体类型)angular 4 Post

时间:2018-04-09 05:50:39

标签: asp.net-core-webapi angular4-httpclient

我正尝试使用angular 4 post方法访问wep api。

在我的服务中,我添加了内容类型的application / json。我在将数据发送到api时将对象转换为json。我正在使用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!");
    }
  );
}}

在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);
    }
}
}

在这里,我想将objtect作为学生模型捕获并对数据执行某些操作。这是学生模型

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

    public string Name { get; set; }

    public double Cgpa { get; set; }
}

但是当使用prostman时,我可以成功地接收到该物体。enter image description here

更新 使用HttpHeaders而不是Headers和CORS解决了这个问题

为ASP.NET Core 2启用CORS =>

在ConfigureServices中:

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

在Configure(Above usemvc())中:

app.UseCors("Cors");

3 个答案:

答案 0 :(得分:5)

您需要更改以下行

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

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

答案 1 :(得分:0)

在我的情况下,导致415错误是因为我在不需要时调用了JSON.stringify(obj)。我在某个地方读到post方法将根据需要对body参数进行字符串化处理

对此深有感触

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

我将其更改为此:

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

这是我的实际工作代码

@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}) ;
  }
}

即使在.NET核心Web API上启用并配置了CORS之后,这还是发生在我身上

答案 2 :(得分:0)

在使用.netcore 2的angular 6时,我遇到了同样的问题。我的代码是这样的:

角度:

  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)

问题通过两种不同的方式解决。

第一个:

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

第二个,尽管我添加了[ApiController]

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

希望有帮助。

相关问题