2

I'm trying to make a simple web api call using jQuery's ajax() function. I have an authorization token I need to pass to the api method in the header. The web api method is working correctly because I tested it out in POSTMAN (a chrome app). In POSTMAN, I use these settings:

URL: http://api.mycompany.com/v1/marketsegments/
Type: GET
Authorization: 32asd1sadf4sa5d6a4sd5as64

I click the send button and I get back the data back that I need.

I have a small web application I created in Visual Studio 2013. When I run the project and use IE10, I get the following errors:

SEC7118: XMLHttpRequest for http://api.mycompany.com/v1/marketsegments/ required Cross Origin Resource Sharing (CORS).
SEC7119: XMLHttpRequest for http://api.mycompany.com/v1/marketsegments/ required CORS preflight.

I think what I'm experiencing is described here:

jQuery, CORS, JSON (without padding) and authentication issues

However, there is no solution that I can follow.

I checked out a lot of material on stack and I'm not sure what I need to do to get the ajax() function working. I've looked at the following links and nothing works:

http://api.jquery.com/jQuery.ajax/

http://api.jquery.com/jQuery.get/

Sending credentials with cross-domain posts?

Unable to send a CORS POST request with jQuery

http://www.html5rocks.com/en/tutorials/cors/#toc-cors-from-jquery

CORS - How do 'preflight' an httprequest?

A CORS POST request works from plain javascript, but why not with jQuery?

How to get a cross-origin resource sharing (CORS) post request working

Cross Origin Resource Sharing - CORS

using jQuery post to ASP.Net webapi

Calling WebApi from jQuery

Web API Put Request generates an Http 405 Method Not Allowed error

405 method not allowed web api

Web API Put Request generates an Http 405 Method Not Allowed error

Access-Control-Allow-Origin Multiple Origin Domains?

HTTPListener "credentials flag" lie

CORS $.ajax session cookies (access-control-allow-credentials & withCredentials=true)

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

Ajax NetworkError: A network error occurred

What causes an HTTP 405 "invalid method (HTTP verb)" error when POSTing a form to PHP on IIS?

http://praneeth4victory.wordpress.com/2011/09/29/405-method-not-allowed/

Post data to RESTful Invalid HTTP status code 405

Jquery Ajax Call to WEB API

http://www.codeproject.com/Articles/424461/Implementing-Consuming-ASP-NET-WEB-API-from-JQuery

How to use Basic Auth with jQuery and AJAX?

Consuming authorized asp.net webapi service using jQuery ajax

Here is the client side code:

<!DOCTYPE html>

<html>
<head>
    <title>Index</title>
    <script src="scripts/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            var token = '32asd1sadf4sa5d6a4sd5as64';
            var $div1 = $('#div1');

            $.ajax({
                contentType: 'application/x-www-form-urlencoded',
                type: 'POST',
                dataType: 'json',
                url: 'http://api.mycompany.com/v1/marketsegments/',
                xhrFields: {
                    withCredentials: true
                },
                beforeSend: function (jqXhr) {
                    jqXhr.setRequestHeader('Authorization', token);
                }
            }).done(function (response) {
                $div1.html(response);
            }).fail(function (response) {
                $div1.html(response.statusText);
            });


            /*

            This code doesn't work, but I've tried all variations of it using the recommendations from the links above.

            $.ajax({
                contentType: 'application/json',
                type: 'GET',
                dataType: 'json',
                crossDomain: true,
                url: 'http://api.mycompnay.com/v1/marketsegments/',
                headers: {
                    "X-Requested-With": "XMLHttpRequest"
                },
                xhrFields: {
                    withCredentials: true
                },
                beforeSend: function (jqXHR) {
                    jqXHR.setRequestHeader('Authorization', token);
                }
            }).done(function (response) {
                $div1.html(response);
            }).fail(function (response) {
                $div1.html(response.statusText);
            });
            */

        });
    </script>
</head>
<body>
    <div id="div1"></div>
</body>
</html>

Here is the web api method:

[HttpGet]
[Route("v1/marketsegments")]
public HttpResponseMessage MarketSegments()
{
    var token = Request.Headers.Authorization.ToString();
    try
    {
        // Check token here...

        // Return the response.
        return Request.CreateResponse(HttpStatusCode.OK, marketSegments, JsonMediaTypeFormatter.DefaultMediaType);
    }
    catch (Exception ex)
    {
        return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
    }
}

Here is my web.config file:

<?xml version="1.0" encoding="utf-8"?>

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <clear />
        <add name="Access-Control-Allow-Origin" value="*" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>
Community
  • 1
  • 1
Halcyon
  • 13,619
  • 17
  • 64
  • 91

1 Answers1

1

It's probably the fact that that specific resource doesn't support what you're trying to do.

When you attempt to send a GET json request to a server with headers, the browser first sends an OPTION request to make sure that you can access it. Unfortunately, this OPTION request cannot carry with it any authentication. This means that if you want to send a GET with auth, the server must allow an OPTION without auth.