我有一个遗留的webforms asp.net网站和一个新的asp.net核心站点共享一个auth cookie。当我尝试使用Typescript
从Axios
(在核心站点中)向Web服务方法(在旧站点中)发出CORS HTTP请求时,除非我传递空数据对象,否则它将失败。例如:
此请求将失败:
const url: string = "http://legacy.mydev.machine:1259/MyService.asmx/GetInformation";
const optionsThatWontWork: AxiosRequestConfig = {
withCredentials: true
};
axios.get(url, optionsThatWontWork)
.then((response) => { console.log(response); })
.catch((error) => { console.log(error); });
浏览器执行1 HTTP GET(无飞行前)请求,该请求返回HTTP 500,并在响应中显示以下消息
“对于意外以'/ GetInformation'结尾的URL,请求格式无法识别。”
但这有效:
const url: string = "http://legacy.mydev.machine:1259/MyService.asmx/GetInformation";
const optionsThatWillWork: AxiosRequestConfig = {
withCredentials: true,
data: {
// Adding this empty data object makes a difference
}
};
axios.get(url, optionsThatWillWork)
.then((response) => { console.log(response); })
.catch((error) => { console.log(error); });
在这种情况下,浏览器发出2个请求。第一个是HTTP OPTIONS请求,返回200,然后第二个是GET成功点击GetInformation
端点并返回带有json数据的200。
比较2个HTTP GET消息时,我能看到的唯一区别是成功的消息有一个Content-Type: application/json;charset=utf-8
头。
我尝试手动添加该标题,但这也不起作用:
const optionsThatStillWontWork: AxiosRequestConfig = {
withCredentials: true,
headers: {
"Content-Type": "application/json;charset=utf-8"
},
};
我使用Owin
在遗留站点的Microsoft.Owin.Cors
管道中配置了CORS:
Private Sub ConfigureCors(ByVal app As IAppBuilder)
Dim corsPolicy = New CorsPolicy() With {
.AllowAnyMethod = True,
.AllowAnyHeader = True,
.SupportsCredentials = True,
.AllowAnyOrigin = False
}
corsPolicy.Origins.Add("http://newsite.mydev.machine:9050")
Dim corsPolicyProvider = New CorsPolicyProvider With {
.PolicyResolver = Function(context) Task.FromResult(corsPolicy)
}
Dim options = New CorsOptions With {
.PolicyProvider = corsPolicyProvider
}
app.UseCors(options)
End Sub
注意:http://legacy.mydev.machine:1259
和http://newsite.mydev.machine:1259
都在我的hosts文件中指向127.0.0.1
的条目。
根据the axios documentation,data
配置选项是
“仅适用于请求方法'PUT','POST'和'PATCH'”
......我同意的。
几个问题然后:
data
对象使这个工作?这似乎是服务器端代码中的一个问题。
Content-Type
自动添加,因为提供了data
。即使对于不发送有效负载的GET请求也是如此。我认为检查处理请求的控制器代码是有意义的。假设应该明确指定内容类型。
顺便说一句,如果CORS预检失败,GET请求就不会有500内部服务器错误。选项预检将失败,下一步将不会有GET请求。