首页 文章

web api 2 CORS否'Access-Control-Allow-Origin' Headers 存在

提问于
浏览
1

嘿所有我有这个Web服务,我试图发送一些JSON:

$.ajax({
      type: "POST",
      crossDomain: true,
      dataType: 'json',
      contentType: 'application/json; charset=utf-8',
      cache: false,
      url: serviceURL + 'theQ',
      headers: {
           'Access-Control-Allow-Origin' : '*',
      },
      data: JSON.stringify({ query: sqlCC, empImg: false }),
      success: function (data) {
          var obj = jQuery.parseJSON(data);
          app.employeeData = obj[0];
      },
      error: function (xhr, status, error) {
          console.log('checker1' + xhr.responseText);
      }
});

我在我的web api 2功能上安装了CORS:

[HttpPost]
[EnableCors(origins: "*", headers: "*", methods: "*")]
[Route("theQ")]
    public IHttpActionResult theQ(theQ.theQVars data)
    {
         .... code here.....
    }

但是当我尝试执行该AJAX时,我在CHROME中得到以下内容:

XMLHttpRequest无法加载http:// dev-zzzz / xxxx / Q / SELECT%20DI ---- D%20ASC / false?_ = 1454534694738 . 请求的资源上不存在“Access-Control-Allow-Origin”标头 . 因此,不允许来源“http://tst-zzzz.com”访问 .

现在,如果我指定*允许,我为什么会收到此错误?

1 回答

  • 2

    我认为你错了CORS .

    Access-Control-Allow-Origin标头应存在于远程站点上不在请求中的HTTP请求的响应中 .

    在某些情况下,浏览器还会发出预检请求 - 使用OPTIONS方法 .

    预检请求的响应应该包含

    各种Access-Control标头

    阅读更多关于此here

    Hovewer您的服务器应根据您的设置添加此标头

    [EnableCors(origins: "*", headers: "*", methods: "*")]
    

    您是否已启用CORS支持?

    尝试在HttpConfiguration上调用enableCors(),如文档here

    using System.Web.Http;
    namespace WebService
    {
        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // New code
                config.EnableCors();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }
    }
    

相关问题