【发布时间】:2026-02-21 05:45:01
【问题描述】:
我有一个 React 应用程序,它通过 POST 方法将 JSON 对象发送到我的 API。我可以使用 Post-man 得到适当的响应,但是从我的应用程序中,存在 CORS 问题。我希望能够将对象发送到我的 API,并让 API 发回一个书面文件。我的 GET 方法可以正常工作。
这是我遇到的错误:
xhr.js:166 OPTIONS http://localhost:57429/api/MiniEntity 404 (Not Found)
Access to XMLHttpRequest at 'http://localhost:57429/api/MiniEntity' from origin
'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't
pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested
resource.
这是我的 React 代码:
var apiUrl = "http://localhost:57429/api/MiniEntity";
axios.post(apiUrl, this.state.entitiesToExport).then(response => {
console.log(response.data);
});
这是我的 C# API 代码:
// Post: api/MiniEntity
[HttpPost]
public HttpResponseMessage PostMiniEntities([FromBody] object value)
{
HttpContext.Response.Headers.Add("access-control-allow-origin", "*");
var json = JsonConvert.SerializeObject(value);
System.IO.File.WriteAllText("output.txt", json);
var dataBytes = System.IO.File.ReadAllBytes("output.txt");
var dataStream = new MemoryStream(dataBytes);
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
httpResponseMessage.Headers.Add("Access-Control-Allow-Origin", "*");
httpResponseMessage.Content = new StreamContent(dataStream);
httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = "output.txt";
httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
httpResponseMessage.Content.Headers.Add("Access-Control-Allow-Origin", "*");
httpResponseMessage.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
httpResponseMessage.Headers.Add("Access-Control-Allow-Methods", "POST, OPTIONS");
return httpResponseMessage;
}
所有标题内容都是我尝试允许访问,但它不起作用。
【问题讨论】:
-
Preflight 在 POST 发生之前发送一个 HTTP OPTIONS 请求,因此在您的 post 命令中设置标头的工作实际上不会被命中。这是 ASP WebApi 2 还是 ASP.NET Core MVC?无论哪种方式,您都应该考虑将 CORS 配置为应用程序启动的一部分。
-
我明白了。我注意到正在发送 OPTIONS 请求,但不知道如何处理。我正在使用 ASP.NET Core MVC。如何配置 CORS?
-
假设 Core 3.0,你应该看看this document。如果您使用的是早期版本的 asp core,请告知我们,以便我们为您提供正确的解决方案。
标签: javascript c# reactjs cors