我正在使用ASP.NET Web API的最终版本来实现一个JavaScript友好的API.根据各种教程,我在web.config中启用了CORS:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)
有了上述,跨域GET和POST请求工作正常,但PUT和DELETE请求都失败.
在Chrome中:
Access-Control-Allow-Methods不允许使用方法PUT.
Access-Control-Allow-Methods不允许使用DELETE方法.
是否需要一些额外的东西来让PUT和DELETE动词跨域工作?
我用过以下内容:
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
正如这里建议的:
在我的项目中启用跨源AJAX请求.一切(POST/PUT/DELETE/GET)昨天都在运行.然后我决定在我的webAPI项目中添加一个新的端点,而这个端点失败了:
> XMLHttpRequest cannot load http://localhost:24144/api/card. Origin
> http://localhost:11089 is not allowed by Access-Control-Allow-Origin.
Run Code Online (Sandbox Code Playgroud)
在我的WebApiConfig中,我做到了这一点:
var cors = new EnableCorsAttribute("http://localhost:11089", "*", "*");
config.EnableCors(cors);
Run Code Online (Sandbox Code Playgroud)
我的AJAX请求与其他工作相同,如下所示:
var updateCard = function (data) {
var options = {
url: apiEndpoint + 'card',
type: 'PUT',
async: true,
dataType: 'json',
data: data,
xhrFields: {
withCredentials: true
}
};
return $.ajax(options)
.done(function (response) {
toastr.success("Card Updated", "Success");
})
.fail(function (msg) {
toastr.error("Could not update card.", "Error");
});
}
};
Run Code Online (Sandbox Code Playgroud)
即使直接在失败的方法或控制器上使用属性,我也会得到同样的错误:
[EnableCors(origins: "http://localhost:11089", …Run Code Online (Sandbox Code Playgroud) 我正在尝试向我的 Web API 发出简单的发布请求,但收到 CORS 错误:
\n\n\n跨源请求被阻止:同源策略不允许读取 https://localhost:5001/expression/add 处的远程资源。(原因:根据 CORS 预检响应中的标头 \xe2\x80\x98Access-Control-Allow-Headers\xe2\x80\x99,不允许使用标头 \xe2\x80\x98content-type\xe2\x80\x99)。
\n
请求如下:
\nexport async function sendPostRequest(request, object) {\n\n try {\n\n const response = await fetch(request, {\n method: \'POST\',\n headers: {\n \'Content-Type\': \'application/json\'\n },\n body: JSON.stringify(object),\n });\n\n const result = await response.json();\n\n return result;\n\n } catch (error) {\n console.error(error);\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n传入该函数的url和对象如下:
\nvar url = \'https://localhost:5001/expression/add\';\n\nvar toSave = {\n \'userId\': 1,\n \'expression\': \'hello\'\n};\nRun Code Online (Sandbox Code Playgroud)\n这是端点:
\n[ApiController]\n[Route("[controller]")]\npublic class ExpressionController : ControllerBase\n{\n [HttpPost]\n [Route("add")]\n …Run Code Online (Sandbox Code Playgroud)