我在[System.Web.Http.Cors.EnableCors(origins: "*", headers: "*", methods: "*")]
之前添加了public class UPWebsiteAPIController : ApiController
,并且每次我想要POST
数据时,我的函数都应return new JsonResult { Data = toReturn };
。问题是该函数已完全执行并返回toRerurn
对象,但浏览器获取错误代码500和
没有Access-Control-Allow-Origin标头存在于请求的内容中 资源
后端代码:
[System.Web.Http.HttpPost]
public async Task<System.Web.Mvc.ActionResult> CreateEvent(FormDataCollection formData)
{
try
{
(code which works fine)
toReturn[0] = HttpStatusCode.OK;
return new JsonResult { Data = toReturn };
}
catch (Exception ex)
{
toReturn[0] = HttpStatusCode.BadRequest;
return new JsonResult { Data = toReturn };
}
}
Fronend代码:
$.ajax({
type: "POST",
url: 'http://www.XXX.aspnet.pl/api/UPWebsiteAPI/CreateEvent',
data: data,
beforeSend: function() {
$loading.show();
},
success: function(response) {
console.log('sukces');
console.log(response);
$loading.hide();
$response.show();
$response.find('.pay-button').show();
$response.find('.pay-link').attr('href', response.Data[1]);
$response.find('h2').html("Gratulacje!' );
},
error: function(response) {
console.log('error');
console.log(response);
$loading.hide();
$response.show();
$('.pay-button').hide();
$response.find('h2').html("Przepraszamy...");
}
});
我该怎么办?有趣的是,有时候工作没有任何问题,有时(经常)会得到这些错误。
答案 0 :(得分:1)
在global.asax.cs文件中添加以下方法。
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE,GET");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "content-type,Access-Control-Allow-Origin,authToken, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}