【发布时间】:2019-07-19 06:19:22
【问题描述】:
我一直在做一个 Angular 项目。我应该通过 Web 服务(ASP.NET Web api 核心)从服务器获取数据。所以 GET 方法可以完美运行,但我不能使用 Post 方法。我得到这个错误
我的发帖方法
[HttpPost]
public IActionResult PostMerchandiser([FromBody] Presentent presentent)
{
using (var db = new DMerchContext(ClientConnectionString))
{
presentent.idElement = Guid.NewGuid().ToString();
presentent.etat = 0;
db.Add(presentent);
db.SaveChanges();
return Ok();
}
}
我也将此添加到我的 web.config 中
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept,
Authorization" />
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Allow-Methods"
value="POST,GET,PUT,DELETE,OPTIONS" />
<add name="Access-Control-Max-Age" value="1728000" />
</customHeaders>
Angular 代码(服务)
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Configuration } from '../Services/Configuration';
import { Merchandiser } from 'src/Models/Merchandiser';
@Injectable()
export class MerchandiserService {
private actionUrl: string;
constructor(public http: HttpClient, public configuration: Configuration)
{
this.actionUrl = configuration.serverWithApiUrl;
}
/////////////////////////////////////////// Login Services
/////////////////////////////////////////
public getMerchandisers<T>(): Observable<T> {
return this.http.get<T>(this.actionUrl +
'Presentents/GetPresentents');
}
public PostMerchandiser<T>(merchandiser: Merchandiser): Observable<T> {
return this.http.post<T>(this.actionUrl+'Presentents/PostMerchandiser',
merchandiser);
}
}
有什么建议吗?
【问题讨论】:
-
你的 Angular 代码在哪里?
-
您必须在服务器 docs.microsoft.com/en-us/aspnet/core/security/… 上启用/设置 CORS 中间件(如果认为 web.config 仅适用于 IIS)
-
@ChristianBenseler 立即查看
-
@WilliamLohan 非常感谢你,终于成功了
标签: angular cors asp.net-core-webapi