【问题标题】:MVC Web API: Response for preflight has invalid HTTP status code 404MVC Web API:预检响应具有无效的 HTTP 状态代码 404
【发布时间】:2017-12-22 14:08:51
【问题描述】:

当我使用它时,我在两个服务器节点上的服务有时运行良好,有时会出错

XMLHttpRequest cannot load.. Response for preflight has invalid HTTP status code 404

我按照stackoverflow上的答案编写了这段代码,但没有解决问题

 protected void Application_BeginRequest()
    {
        if (Request.HttpMethod == "OPTIONS")
        {
            Response.Flush();
        }
    }

Web.config

  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <remove name="X-Powered-By" />
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Accept, Content-Type, Origin" />
        <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
    </security>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>

【问题讨论】:

标签: c# jquery angularjs asp.net-mvc asp.net-web-api


【解决方案1】:

你可能需要一个带有[WebInvoke(Method = "OPTIONS", UriTemplate = "*")]这个装饰的操作合约,例如:

    [OperationContract]
    [WebInvoke(Method = "OPTIONS", UriTemplate = "*")]
    void GetOptions();

操作实现是:

    public void GetOptions()
    {
        WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
        WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
        WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
    }

【讨论】:

  • 感谢您的帮助和努力。你能告诉我在我的服务项目中我把你的代码放在哪里吗?
  • 操作契约应该放在客户端调用遇到错误的同一个服务契约中,操作实现应该放在各自的服务类中。
猜你喜欢
  • 2017-08-24
  • 2017-09-26
  • 1970-01-01
  • 2018-04-25
  • 2016-01-22
  • 1970-01-01
  • 2018-03-12
  • 2016-02-13
  • 2016-01-18
相关资源
最近更新 更多