1

我用 oData 创建了一个 Web API 并由 datajs 调用,所以它在 IE 上运行良好,但在其他浏览器中运行良好。代码如下

我的控制器类是

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();
    }

}

和公司类别是

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

下面是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
        }
    );
}

我也添加了

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

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

现在我用这种方式打电话。

<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>

这对 IE 运行良好,但不适用于 Chrome 和 Firefox。

请帮忙。

下面是我在 IE 浏览器中的请求 HttpRequestMessage

当 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

最大数据服务版本:3.0 }}

Chrome 浏览器中的 HttpRequestMessage

  {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
}}
4

1 回答 1

2

由于跨域请求问题,请求未正确发送。

IE 允许跨域请求,但其他浏览器(Chrome 和 FF)不允许跨域请求。

为了解决这个问题,您可以使用 JsonP,Datajs 在请求中添加了一个旋钮以启用使用 JsonP,即

enableJsonpCallback: true

你把它设置为假。在启用 JsonP 的情况下,响应将始终是 json 并且服务应该支持它。

要了解有关跨域问题的更多信息,您可以查看:

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

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


于 2013-05-14T23:19:00.937 回答