我正在尝试向ASP.NET MVC控制器操作方法发出CORS AJAX请求。 我尝试了从domain1到domain2的以下ajax请求 -
$.ajax({
type: "POST",
url: "http://domain2/Home/SendMail",
data: JSON.stringify({ name: name, emailaddress: email}),
contentType: "application/json; charset=utf-8",
dataType: "json",
xhrFields: {
withCredentials: true
},
success: function (response) {
console.log(response);
}
});
domain2中的操作方法
[HttpPost]
public ActionResult SendMail(string name, string emailaddress)
{
try
{
HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");
HttpContext.Response.AppendHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
HttpContext.Response.AppendHeader("Access-Control-Max-Age", "3600");
HttpContext.Response.AppendHeader("Access-Control-Allow-Headers", "x-requested-with");
HttpContext.Response.AppendHeader("Access-Control-Allow-Credentials", "true");
//I also tried the following method, but result is same.
//HttpContext.Response.Headers.Set();
return Json("success");
}
catch (Exception Ex)
{
return Json(Ex.Message);
}
}
但我仍然收到此错误
XMLHttpRequest cannot load http://domain2/Home/SendMail.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:5153' is therefore not allowed access.
任何帮助?