在前端开发中,跨域请求问题是一个常见且令人头疼的问题。本文将通过一个实际案例,详细介绍如何在Angular 17和ASP.NET Core(.NET 8)之间配置CORS(跨源资源共享),以确保请求能够正常工作。
问题描述
当尝试从Angular 17应用向ASP.NET Core服务器发送请求时,可能会遇到如下的错误信息:
Access to XMLHttpRequest at ‘http://localhost:5000/api/user’ from origin ‘https://localhost:4200’ 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.
这个错误表明,服务器没有在响应头中提供Access-Control-Allow-Origin
头信息,从而导致浏览器阻止了跨域请求。
配置CORS
服务端配置
首先,我们需要在ASP.NET Core应用程序中配置CORS。下面是如何在Program.cs
中配置的步骤: