【问题标题】:CORS Pre-flight error when contacting self-hosted WebApi service联系自托管 Web Api 服务时出现 CORS 预检错误
【发布时间】:2018-01-17 12:38:01
【问题描述】:

当 Web 门户与位于 Web 门户服务器之外的其他服务器中的自托管 WebAPI 服务联系时,我收到此错误:

对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。起源 'someportaldomain' 因此不是 允许访问。

自托管服务总是在每个响应中返回“Access-Control-Allow-Origin”标头,但如果浏览器决定在调用 url 之前进行预检,用户会在 js 控制台上收到此错误。

【问题讨论】:

    标签: asp.net asp.net-mvc cors preflight


    【解决方案1】:

    我在这里发布答案,因为我没有找到任何直接的答案,不得不从几个帖子中拉出来。

    解决方案是在自托管服务中添加 Options 方法,如下所示:

    [ServiceContract]    
    public interface IACT_HttpService
    {
        //[FaultContract(typeof(ValidationFault))]
        [WebInvoke(Method = "OPTIONS", UriTemplate = "*")]
        void GetOptions();
    
      //My other methods
      ...
    }
    
    
    public class ACT_HttpService : IACT_HttpService
    {
        //Adjust this method to restrict the origin as needed
        public void GetOptions()
        {
            log.Debug("Get options fired");
            //These headers are handling the "pre-flight" OPTIONS call sent by the browser
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTIONS");
            //Add here any special header you have
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
            WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-A}llow-Origin", "*");            
    
            WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-12
      • 2015-02-04
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-01
      相关资源
      最近更新 更多