Skip to main content
 首页 » 编程设计

c#之将正确的 header 值发送到从 Angular $http 到 asp.net webapi 的 Preflight 请求时出错

2024年01月26日29Renyi-Fan

我正在尝试使用 Angular 的 $http 将身份验证数据发送到后端 Web API。当我添加以下行时,浏览器开始发送预检请求

$http.defaults.headers.common.Authorization = 'Basic xxxxyyyyyy' ; 

从 web api 端,当我收到一个带有 OPTIONS 方法的请求时,我会按如下方式处理它。

if (request.Method == HttpMethod.Options && request.Headers.Any(k => k.Key.Contains("Origin"))) 
            { 
                var response = new HttpResponseMessage(HttpStatusCode.OK); 
                response.Headers.Add("Access-Control-Allow-Headers", "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name"); 
                response.Headers.Add("Access-Control-Allow-Origin", request.Headers.GetValues("Origin")); 
                response.Headers.Add("Access-Control-Allow-Credentials", "true"); 
                response.Headers.Add("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS"); 
                var tsc = new TaskCompletionSource<HttpResponseMessage>(); 
                tsc.SetResult(response); 
                return tsc.Task;   
            } 

但是预检请求没有通过访问控制检查。

XMLHttpRequest cannot load http://localhost:53024/api............. Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:9000, *', but only one is allowed. Origin 'http://localhost:9000' is therefore not allowed access.

我做错了什么?

请您参考如下方法:

“Access-Control-Allow-Origin header contain multiple values”错误解决方案在此 link 中给出.请试一试。

希望对您有所帮助!