【问题标题】:Fetching value from post request gives Method not allowed从发布请求中获取值给出了不允许的方法
【发布时间】:2017-06-26 13:10:09
【问题描述】:

很抱歉再次提出类似的令人沮丧的问题,但我无法从 Angular2 配置对 Web API 2 的 http POST 请求

fetchBattingAverage() {
    let str = JSON.stringify({"foo": "bar"});
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });


    // JSON.stringify({ "abc": "def" })
    return this._http.post(
      this.baseURL + 'getBatting',
      str,
      options
    )
      .map(res => res.json());
  }

Web API 2:网络配置

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
    <add name="Access-Control-Allow-Headers" value="*" />
    <add name="Access-Control-Allow-Methods" value="*" />
  </customHeaders>
</httpProtocol>

Web API 2.2 控制器:

[RoutePrefix("api")]
public class SachinController : ApiController
{
        [HttpPost]
        [Route("getBatting")]
        [EnableCors(origins: "*", headers: "*", methods: "*")]
        public IHttpActionResult Post([FromBody] string countries)
        {
            // Do something
            return Ok()
        }

错误信息:

OPTIONS http://localhost:54094/api/getBatting 405 (Method Not Allowed)
Response for preflight has invalid HTTP status code 405

请求标头:

OPTIONS /api/getBatting HTTP/1.1
Host: localhost:54094
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: POST
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
DNT: 1
Referer: http://localhost:4200/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8

【问题讨论】:

  • 删除自定义标头会导致消息:“请求通过访问控制检查:请求的资源上不存在'Access-Control-Allow-Origin'标头。无论如何感谢链接。
  • 因此,通过删除请求中的自定义标头,您避免了浏览器发送 OPTIONS 请求的需要,但如果您仍然收到“没有 'Access-Control-Allow-Origin' 标头”存在于请求的资源上”,那么您的服务器配置显然尚未按预期工作,因此请查看我的答案或尝试stackoverflow.com/questions/20079813/… 中的答案中的步骤

标签: angular cors asp.net-web-api2


【解决方案1】:

显然 Web.Config 中有另一个属性需要删除。

<system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />   <!-- Remove this -->
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <httpProtocol>
    </httpProtocol>
  </system.webServer>

【讨论】:

    猜你喜欢
    • 2012-01-04
    • 2021-08-27
    • 2018-03-07
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 2020-03-19
    • 2020-01-15
    • 1970-01-01
    相关资源
    最近更新 更多