JavaScript-Access-Control-Allow-Methods似乎不起作用

我在网络服务器上安装了一个小型Web API应用程序,其中一个GET方法返回3条记录,而POST方法则接受一个对象,然后为其分配ID并返回相同的对象.

我正在从本地Web应用程序进行Ajax调用,并测试了我的CORS实现.到目前为止,几乎所有内容都运行良好.如果我未指定Access-Control-Allow-Origin(现在仅设置为*),则不允许拨打电话(我期望的是),但是我也尝试指定Access-Control-Allow-Methods,但它没有似乎我的输入限制了进行特定的呼叫.

例如,这是我的web.config包含的内容

<httpProtocol>
  <customHeaders>
    <clear />
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="Content-Type, Authorization, Accept, X-Requested-With " />
    <add name="Access-Control-Allow-Methods" value="OPTIONS, GET" />
  </customHeaders>
</httpProtocol>

我只列出了OPTIONS和GET,但是我仍然可以发出POST请求.同样,如果将其设置为“ OPTIONS,POST”,我仍然可以发出GET请求.

编辑

根据下面@geekonaut的回答,我能够按预期看到此功能.我尝试尝试一个PUT请求,而不是GET或POST,但是我收到一个错误,提示不允许OPTIONS(预检)请求.我首先需要在Global.asax.cs文件添加一个部分来接受该方法,然后,如果我在web.config的Access-Control-Allow-Methods值中切换添加/删除PUT,我看到它只会允许方法(如果已列出).

protected void Application_OnBeginRequest()
{
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.StatusCode = 200;
        HttpContext.Current.Response.End();
    }
}

解决方法:

CORS不会阻止基于其方法的简单(甚至预检)POST请求.

例如,Access-Control-Allow-Methods仅对无法使用简单跨域格式进行的请求有效.

这意味着:GET和POST可以跳过the spec中描述的Access-Control-Allow-Methods:

Simple cross-origin requests generated outside this specification
(such as cross-origin form submissions using GET or POST or
cross-origin GET requests resulting from script elements) typically
include user credentials, so resources conforming to this
specification must always be prepared to expect simple cross-origin
requests with credentials.

Because of this, resources for which simple requests have significance
other than retrieval must protect themselves from Cross-Site Request
Forgery (CSRF) by requiring the inclusion of an unguessable token in
the explicitly provided content of the request.

(强调我的)

相关文章

IE6是一个非常老旧的网页浏览器,虽然现在很少人再使用它,但...
PHP中的count()函数是用来计算数组或容器中元素的个数。这个...
使用 AJAX(Asynchronous JavaScript and XML)技术可以在不...
Ajax(Asynchronous JavaScript and XML)是一种用于改进网页...
本文将介绍如何通过AJAX下载Excel文件流。通过AJAX,我们可以...
Ajax是一种用于客户端和服务器之间的异步通信技术。通过Ajax...