【发布时间】:2018-04-09 05:50:39
【问题描述】:
我正在尝试使用 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; }
}
更新 使用 HttpHeaders 而不是 Headers 和 CORS 解决了这个问题
为 ASP.NET Core 2 启用 CORS =>
在配置服务中:
services.AddCors(options => options.AddPolicy("Cors", builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
在配置中(在 usemvc() 上方):
app.UseCors("Cors");
【问题讨论】:
-
用这个编辑过的答案救了我的命! THX
-
我们在哪里可以找到启动类中的 ConfigureServices 和 Configure ?你能展示如何添加这些
-
@SujayUN 这些是在创建项目时创建的方法,在 Startup.cs 文件中进行搜索,您会找到它们
标签: asp.net-core-webapi angular4-httpclient