我有一个用 C# 创建的简单 Web api,它是一个返回字符串的方法
public string Get()
{
return "Welcome Web API online";
}
我现在通过javascript调用它,它成功击中了母鹿,但它不会返回任何数据,它总是陷入错误函数,
var url = "https://localhost:44381/api/accounts";
$.ajax({
type: 'GET',
dataType: 'json',
url: url,
success: function (data) {
console.log(data);
},
error: function (data) { console.log(data); }
});
检查控制台日志,显示:
跨源请求被阻止:同源策略不允许读取 https://localhost:44381/api/accounts 处的远程资源?
请赐教。
最佳答案
当我们使用 Ajax、Angular 等访问具有不同源的 URL 时,需要在不同源端处理 CORS(跨源请求共享)。 将以下代码添加到您的 Web api 项目中。在 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", "GET, POST, PUT, DELETE");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
我对你有帮助。这对我有用。
关于javascript - AJAX 不会从 Web api C# 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57917763/