Asp.net-Core-Webapi

415(不支持的媒體類型)角度 4 Post

  • February 25, 2022

我正在嘗試使用 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);
   }
}
}

在這裡,我想將對象擷取為學生模型並對數據進行處理。這是學生模型

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

   public string Name { get; set; }

   public double Cgpa { get; set; }
}

但是在使用prostman時,我可以成功接收到對象。在此處輸入圖像描述

UPDATE 使用 HttpHeaders 而不是 Headers 和 CORS 解決了這個問題

為 ASP.NET Core 2 啟用 CORS =>

在配置服務中:

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

在配置中(高於 usemvc()):

app.UseCors("Cors");

您需要更改以下行

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

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

在我的情況下,導致 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 後,這也發生在我身上

引用自:https://stackoverflow.com/questions/49726333