1

i have created a Web API with oData and calling by datajs so it is running fine for IE but not in other browsers. The code is as below

my Controller class is

public class CompanyController: EntitySetController < CompanyDto, string > {
    List < CompanyDto > companyDto = new List < CompanyDto > () {
         new CompanyDto() {
             Id = 1,
             CompanyName = "ABC",
             Address1 = "ABC -Address",
             HeadCount = 100
         },
         new CompanyDto() {
             Id = 2,
             CompanyName = "MNO",
             Address1 = "MNO -Address",
             HeadCount = 203
         },
         new CompanyDto() {
             Id = 3,
             CompanyName = "XYZ",
             Address1 = "XYZ -Address",
             HeadCount = 33
         } 
    }; 

    [Queryable]
    public override IQueryable < CompanyDto > Get() {
        return companyDto.AsQueryable();
    }

}

and Company Class is

public class CompanyDto {
    public int Id {
        get;
        set;
    }
    public string CompanyName {
        get;
        set;
    }
    public string Address1 {
        get;
        set;
    }
    public int HeadCount {
        get;
        set;
    }
}

below is the method of WebApiconfig

public static void Register(HttpConfiguration config) {
    //Routing for oData routing
    ODataModelBuilder modelBuilder = new ODataConventionModelBuilder();
    modelBuilder.EntitySet < CompanyDto > ("Company");


    Microsoft.Data.Edm.IEdmModel model = modelBuilder.GetEdmModel();
    config.Routes.MapODataRoute("ODataRoute", "odata", model);
    config.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json");
    config.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml");

    //Routing for Postmark api call for value controller.
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new {
            id = RouteParameter.Optional
        }
    );

    config.Routes.MapHttpRoute(
        name: "Api UriPathExtension",
        routeTemplate: "api/{controller}.{extension}/{id}",
        defaults: new {
            id = RouteParameter.Optional, extension = RouteParameter.Optional
        }
    );

    config.Routes.MapHttpRoute(
        name: "Api UriPathExtension ID",
        routeTemplate: "api/{controller}/{id}.{extension}",
        defaults: new {
            id = RouteParameter.Optional, extension = RouteParameter.Optional
        }
    );
}

also I have added

GlobalConfiguration
     .Configuration
     .Formatters
     .XmlFormatter
     .AddUriPathExtensionMapping("xml", "text/xml");

GlobalConfiguration
     .Configuration
     .Formatters
     .XmlFormatter
     .AddUriPathExtensionMapping("json", "application/json");

Now I am calling by this way.

<script src="../../Scripts/datajs-1.1.0.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
    success = function (data) {
        debugger;
        $.each(data.results, function (key, val) {
            var str = val.CompanyName + ': ' + val.Address1 + ': ' + val.HeadCount;
            $('<li/>', {
                text: str
            })
                .appendTo($('#products'));
        });
    };

    error = function (err) {
        debugger;
        $('<li/>', {
            text: err
        })
            .appendTo($('#products'));
    };

    function CallOdataByOdataJS() {
        debugger;
        OData.read({
            requestUri: "http://localhost:50141/odata/Company",
            enableJsonpCallback: false,
            headers: {
                "Token": "Shyam"
            },
            method: "GET"

        },
        success, error);
    }
</script>

this is running fine for IE but not for Chrome and Firefox.

Please help.

below is my request HttpRequestMessage in IE Browser

When OData.defaultHttpClient.enableJsonpCallback = false;

 {Method: GET, RequestUri: 'http://localhost:51818/odata/Projects', Version: 1.1, Content:          System.Net.Http.StreamContent, Headers:
 {
  Connection: Keep-Alive
  Accept: application/atomsvc+xml; q=0.8
  Accept: application/json; odata=fullmetadata; q=0.7
  Accept: application/json; q=0.5
  Accept: */*; q=0.1
  Accept-Encoding: gzip
  Accept-Encoding: deflate
  Accept-Language: en-us
  Cookie: ASP.NET_SessionId=ymsivdoh5zmgxmmstvkevugx
  Host: localhost:51818
  Referer: http://localhost:52952/CoreconWebApiClient/Projects.aspx
  User-Agent: Mozilla/5.0
  User-Agent: (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
  Authorization-Token:    94,214,182,1,98,51,181,18,190,167,152,19,225,97,211,221,145,78,188,26,247,172,226,13,90,113,105,2,226     ,15,137,12,190,22,95,226,215,9,111,95,162,33,36,220,238,197,99,169,158,140,170,61,3,186,190,97,2   44,173,125,212,3,135,172,111,235,229,133,101,234,188,104,188,127,10,188,221,72,120,48,25,184,56,215,8 0,87,83,117,30,57,241,133,80,137,220,185,220,230,0,20,122,181,0,106,69,234,27,106,212,187,77,77,27,39,159,31,253,140,105,43,167,210,238,35,71,44,251,180,199

MaxDataServiceVersion: 3.0 }}

HttpRequestMessage in Chrome Browser

  {Method: OPTIONS, RequestUri: 'http://localhost:51818/odata/Projects', Version: 1.1, Content:      System.Net.Http.StreamContent, Headers:
{
 Connection: keep-alive
 Accept: */*
 Accept-Charset: ISO-8859-1
 Accept-Charset: utf-8; q=0.7
 Accept-Charset: *; q=0.3
 Accept-Encoding: gzip
 Accept-Encoding: deflate
 Accept-Encoding: sdch
 Accept-Language: en-US
 Accept-Language: en; q=0.8
 Host: localhost:51818
 Referer: http://localhost:52952/CoreconWebApiClient/Projects.aspx
 User-Agent: Mozilla/5.0
 User-Agent: (Windows NT 6.1)
 User-Agent: AppleWebKit/537.11
 User-Agent: (KHTML, like Gecko)
 User-Agent: Chrome/23.0.1271.97
 User-Agent: Safari/537.11
 Access-Control-Request-Method: GET
 Origin: http://localhost:52952
 Access-Control-Request-Headers: origin, maxdataserviceversion, accept, authorization-token
}}
Ram Sharma
  • 21
  • 4
  • Since this is working in IE, but not other browsers, you know that this is a client-side issue, not a server-side problem. So, the Web Api bit is irrelevant to your problem. It's the javascript / datajs that is causing issues. Given that, what exactly do you mean by "not running fine" for Chrome and Firefox? Do you see javascript errors? Is your `error` function getting called? Something else? – Jen S May 10 '13 at 16:21
  • I also recommend using [Fiddler](http://fiddler2.com/) (or something similar) to compare the request and response bodies & headers of the requests in IE vs Chrome/Firefox. They should be the same, and if not, you have more information to work with. – Jen S May 10 '13 at 16:25
  • I means When i am calling from Chrome and Firfox then Request is going to the server but it is not correct format request so every time i am gettign error in call back. – Ram Sharma May 13 '13 at 05:28
  • Could you modify your question to include the error response payload and headers? (It would also be useful to see the request being sent from IE vs the request being sent from Chrome/Firefox) – Jen S May 13 '13 at 06:16

1 Answers1

2

The request is not sent right because of the cross domain request issue.

IE allows cross domain requests, but other browsers (Chrome and FF ) don’t allow cross domain requests.

In order to work around this problem you can use JsonP, Datajs adds a knob in the request to enable using JsonP which is

enableJsonpCallback: true

And you have that set as false. In the case of enabling JsonP, the response will always be json and the service should be supporting it.

To know more about the cross domain issue you can check:

http://datajs.codeplex.com/wikipage?title=OData%20Security&referringTitle=Documentation

http://datajs.codeplex.com/wikipage?title=Cross%20Domain%20Requests&referringTitle=Documentation


  • Note: you'll also need to enable JsonP support on your Web API service. Look here for a discussion of that: http://stackoverflow.com/questions/9421312/jsonp-with-asp-net-web-api – Jen S May 14 '13 at 23:41