asp.net - ASP.NET webform 访问控制允许 orgin 不起作用?
问题描述
我有一个 ASP.NET WebForms 项目。在按钮单击事件中,我调用 JavaScript 方法来执行 XMLHttpRequest 以获取 JSON 格式的所有国家/地区名称。我得到一个访问控制允许来源错误。我如何解决它?
var url = "http://country.io/names.json";
function meth1() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.status == 200 && xmlhttp.readyState == 4) {
console.log("ready " + this.readyState + " status " + this.status);
console.log(this.response);
}
}
xmlhttp.open("get", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send();
}
<form id="form1" runat="server">
<div>
<h4>Test xmlhttprequest on cors</h4>
<input type="button" value="Get ajax cors" onclick="meth1()" />
</div>
</form>
这是我在服务器端设置的代码:
protected void Application_BeginRequest(object sender, EventArgs e)
{
var context = HttpContext.Current;
context.Response.AddHeader("Access-Control-Allow-Origin", "*");
context.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:53410/");
context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
context.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
}
解决方案
您正在向未设置Access-Control-Allow-Origin
标头 ( http://country.io/names.json ) 的网站发出请求。如果您OPTIONS
向该 URL 发出请求,您将获得以下结果:
<h1>403 Forbidden</h1>
<ul>
<li>Code: AccessForbidden</li>
<li>Message: CORSResponse: CORS is not enabled for this bucket.</li>
<li>Method: GET</li>
<li>ResourceType: BUCKET</li>
</ul>
这意味着如果您XMLHttpRequest
对本网站进行操作,您的浏览器将自动阻止响应。
您可以下载并保存 JSON 文件并将其存储在本地服务器上,以便您可以通过XMLHttpRequest
.
例如:
var url = "http://localhost:<portnumber>/names.json";
function meth1() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.status == 200 && xmlhttp.readyState == 4) {
console.log("ready " + this.readyState + " status " + this.status);
console.log(this.response);
}
}
xmlhttp.open("get", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send();
}
推荐阅读
- ios - iOS:带有 SecureEntry 的 UITextField 有时会用“强密码”文本突出显示黄色,然后键盘卡住
- c# - DataGridView 中的 DefaultCellStyle.FormatProvider
- c# - 为什么我的 streamwriter 不写入我的文件?
- node.js - 分组记录并分别获取组的总和
- caching - 谷歌云存储:手动清除缓存
- ios - Xcode 12 SwiftUI 应用程序因 UIRequiredDeviceCapabilities plist 键而被拒绝
- karate - 空手道框架中 REST API 的 NTLM 身份验证
- javascript - 如何按模板拆分字符串
- javascript - 如何在 AngularJS 中超时或延迟工作
- math - 四分位数和旋转