我正在尝试对ASP.NET MVC控制器操作执行跨域POST请求.此控制器操作接受并使用各种参数.问题是,当预检请求发生时,控制器操作实际上会尝试执行,因为OPTIONS请求没有传递任何数据,控制器操作会抛出500 HTTP错误.如果我删除使用该参数的代码或参数本身,则整个请求链成功完成.
这是如何实现的一个例子:
控制器动作
public ActionResult GetData(string data)
{
return new JsonResult
{
Data = data.ToUpper(),
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
Run Code Online (Sandbox Code Playgroud)
客户端代码
<script type="text/javascript">
$(function () {
$("#button-request").click(function () {
var ajaxConfig = {
dataType: "json",
url: "http://localhost:8100/host/getdata",
contentType: 'application/json',
data: JSON.stringify({ data: "A string of data" }),
type: "POST",
success: function (result) {
alert(result);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error: Status: ' + textStatus + ', Message: ' + errorThrown);
}
};
$.ajax(ajaxConfig);
});
});
</script> …
Run Code Online (Sandbox Code Playgroud) 我在 ASP.net Core 2(Windows 身份验证)上有一个 API,在 angular 上有一个前端。我进行了 cors 配置以从 SPA 角度查询我的后端,但由于预检而被 IIS 服务器拒绝,因为他没有身份信息而被阻止。
错误信息 :
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://XXXXXX' is therefore not allowed access. The response had HTTP status code 401.
Run Code Online (Sandbox Code Playgroud)
代码侧正面:
//MY HEADER
private headers = new Headers({
'Content-Type': 'application/json',
'Access-Control-Allow-Credentials':'true',
'Access-Control-Allow-Origin':'true'
});
//REQUEST
let options = new RequestOptions({headers:this.headers, withCredentials:true});
return this.http.get(this.tasksUrl,options).map(res=>res.json());
Run Code Online (Sandbox Code Playgroud)
代码背面:(Startup.cs)
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddCors(options =>
{ …
Run Code Online (Sandbox Code Playgroud) javascript windows-authentication cors asp.net-web-api preflight