Jao*_*han 6 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!");
}
);
}}
Run Code Online (Sandbox Code Playgroud)
在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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我想将objtect捕获为Student模型,并对数据进行处理。这是学生模型
public class Student
{
[Key]
public int ID { get; set; }
public string Name { get; set; }
public double Cgpa { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
使用HttpHeaders而不是Headers和CORS的UPDATE解决了该问题
为ASP.NET Core 2启用CORS =>
在ConfigureServices中:
services.AddCors(options => options.AddPolicy("Cors", builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
Run Code Online (Sandbox Code Playgroud)
在Configure(在usemvc()以上)中:
app.UseCors("Cors");
Run Code Online (Sandbox Code Playgroud)
您需要更改以下行
headers = { headers: new Headers({ 'Content-Type': 'application/json' })
};
Run Code Online (Sandbox Code Playgroud)
至
headers={
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
Run Code Online (Sandbox Code Playgroud)
就我而言,415 错误是因为我JSON.stringify(obj)在不需要的时候调用的。我在某处读到 post 方法将根据需要对 body 参数进行字符串化
所以代替这个:
this._http
.post(
this.baseUrl + 'home/Save',
JSON.stringify(this.obj),
this.headers
)
Run Code Online (Sandbox Code Playgroud)
我把它改成这样:
this._http
.post(
this.baseUrl + 'home/Save',
this.obj, // << no need to stringify
this.headers
)
Run Code Online (Sandbox Code Playgroud)
这是我的实际工作代码
@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}) ;
}
}
Run Code Online (Sandbox Code Playgroud)
即使在 .NET core Web api 上启用并配置 CORS 后,我也发生了这种情况
| 归档时间: |
|
| 查看次数: |
10104 次 |
| 最近记录: |