【发布时间】:2019-10-11 23:17:51
【问题描述】:
我正在从我的 Angular 客户端应用程序向 .NET 核心 Web API 发送 http 请求。虽然我启用了 CORS,但我收到了 CORS 错误。当我向我的 SearchController 发送一个 GET 请求时,它通过就好了,但是当我向我的 FormController 发送一个 POST 请求时,我得到了 CORS 错误。
我尝试在 chrome 中运行它,结果相同。
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors(builder =>
builder.AllowAnyOrigin()
);
app.UseHttpsRedirection();
app.UseMvc();
}
如您所见,我已将其配置为允许任何来源
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'my-auth-token',
})
};
@Injectable()
export class SendFormService
{
submitUrl : string = "https://localhost:5001/api/submitForm";
constructor(private http : HttpClient){ }
public SendFormData(formData : RoadmapForm) : Observable<RoadmapForm>
{
//remember to error handle
return this.http.post<RoadmapForm>(this.submitUrl, formData, httpOptions);
}
}
不工作的 POST 请求
public class Form
{
string title;
string summary;
string body;
string[] tags;
}
[Route("api/submitForm")]
[ApiController]
public class FormController : ControllerBase
{
[HttpPost]
public void Post([FromBody] Form formData)
{
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(formData);
}
}
FormController 类
就像我之前说的,它适用于对我的 SearchController 的 GET 请求。但由于某种原因,我在对 FormController 的 POST 请求中收到了 CORS 错误。
【问题讨论】:
-
POST请求响应的HTTP状态码是什么?使用浏览器开发工具中的网络窗格进行检查。是 4xx 还是 5xx 错误而不是 200 OK 成功响应?
标签: c# angular asp.net-core .net-core asp.net-core-mvc