Search code examples
c#backbone.jsasp.net-web-api

Cannot load web api method using Backbone.js


I have a blank asp.net solution with 5 different projects. One of them is asp.net web api and other one is blank web site with bunch of html pages. I am using backbone.js/jQuery to make calls to the web api within the solution. My blank web site is running on different port and my web api is running on different port.

//Collection
var AuditsCollection = Backbone.Collection.extend({

    url: 'http://localhost:56501/api/searchaudits',

    sync: function (method, model, options) {
                if (!options.crossDomain) {
                    options.crossDomain = true;
                }

                options.timeout = 1000;
                alert(method + ": " + JSON.stringify(model));
                return Backbone.sync(method, model, options);
            },
});
var audits = new AuditsCollection();

// Model
var Audit = Backbone.Model.extend({ });
var audit = new Audit({ auditNumber: "A12" });

audits.add(audit);

// POST CALL - I am sending this model and expecting back another JSON object in response.

 audit.save({}, {

    success: function (response) {
        alert("Got audits successfully" + response);
    },
    error: function (response) {

        alert("Error.. Go home now");
    }
});

I still get this error

XMLHttpRequest cannot load http://mydomain:56501/api/searchaudits. Request header field Content-Type is not allowed by Access-Control-Allow-Headers.


Solution

  • I think I figured out what the issue is. The project is setup in the following structure.

    Error:

    -- Solution

    -- Project 1 (Web API) - running on `http://localhost:80/api`
    
    -- Project 2
    
    -- Project 3
    
    -- Project 4 (Views) - running on `http://localhost:3000/`
    

    So when I started making ajax requests, it started giving exceptions like

    XMLHttpRequest cannot load http://localhost:80/api/searchaudits. Request header field Content-Type is not allowed by Access-Control-Allow-Headers.

    OPTIONS localhost:80/api/searchaudits 405 (Method Not Allowed)

    XMLHttpRequest cannot load /api/searchaudits

    I did not know that it is going to consider domains with different ports ad different domains.

    Solution:

    Override Backbone.Sync method - reference

    In your Web Api projects web.config file, add the following

    <system.webServer>
        <httpProtocol>
              <customHeaders>
                <add name="Access-Control-Allow-Origin" value="*" />
                <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept"/>
              </customHeaders>
            </httpProtocol>
    </system.webServer>
    

    There are answers in StackOverflow regarding this issue in bits and pieces, but this is an effort to put the complete solution together in one place.