【问题标题】:Ajax: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource atAjax:跨域请求被阻止:同源策略不允许读取远程资源
【发布时间】:2018-04-20 20:36:57
【问题描述】:

我在(两台服务器)上托管了 MVC Web API 服务

当我通过 C#(如 WebClient 和 HttpClient)使用它时,它工作正常,当我也通过 Postman 使用它时,它工作,我通过在浏览器中粘贴服务 URL 来调用它,它也工作正常,但是当我通过 jquery 使用它时它工作,有时不工作,并得到以下错误

跨域请求被阻止:同源策略不允许读取 myservice.com 上的远程资源(原因:CORS 预检通道未成功)。

The request details from Postman

【问题讨论】:

  • 您是否尝试安装 fiddler 并深入查看响应消息?
  • 浏览器中显示的网站网址是什么?您尝试使用 jquery 访问的 URL 是什么?

标签: c# jquery angularjs ajax asp.net-web-api2


【解决方案1】:

我们通过这种方式解决了这个问题,我们在 WebApiConfig.Register()-Method 中注册了一个 PreflightRequestHandler(在 Route-configuration 之后)

config.MessageHandlers.Add(new PreflightRequestsHandler());

这是处理程序的实现:

using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace someNamespace 
{
    public class PreflightRequestsHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request.Headers.Contains("Origin") && request.Method.Method.Equals("OPTIONS"))
            {
                var response = new HttpResponseMessage { StatusCode = HttpStatusCode.OK };
                var tsc = new TaskCompletionSource<HttpResponseMessage>();
                tsc.SetResult(response);
                return tsc.Task;
            }

            return base.SendAsync(request, cancellationToken);
        }
    }
}

您可能希望以不同的方式处理 Preflight,但据我所知,这解决了我们的 cors 问题。

【讨论】:

    猜你喜欢
    • 2014-07-20
    • 2021-04-04
    • 2014-10-17
    • 2015-07-22
    • 1970-01-01
    相关资源
    最近更新 更多