微风的executeQuery Q承诺失败CORS [英] Breeze executeQuery Q promise fails CORS

查看:214
本文介绍了微风的executeQuery Q承诺失败CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在用微风消费OData的服务出了问题,我成立了一个Web API的OData服务通过以下的本指南,从提琴手它做工精良预期,但是当我尝试用微风使用它失败,并给出了一个错误信息OK:

I'm having a problem with consuming OData Services using Breeze, I set up a Web API OData service by following this guide, from Fiddler it works excellent as expected, but when I try to use it with breeze it fails and gives an error message of "OK":

[Q] Unhandled rejection reasons (should be empty):Error: OK

使用招我看到它去和元数据的查询,然后将查询其正确返回的实体,这可能是这里的问题?

Using fiddler I see it goes and queries for metadata and then it queries for the entities which are returned correctly, what could be the problem here?

breeze.config.initializeAdapterInstances({ dataService: "OData" });
var manager = new breeze.EntityManager(serverAddress);

var query = new breeze.EntityQuery.from("Laboratories");

manager.executeQuery(query).then(function (data) {
    ko.applyBindings(data);
}).fail(function (e) {
    alert(e);
});

我启用了CORS使用的<一个每晚构建href=\"https://aspnetwebstack.$c$cplex.com/wikipage?title=CORS%20support%20for%20ASP.NET%20Web%20API&referringTitle=Specs\"相对=nofollow>的ASP.NET Web API CORS支持,这一切工作正常,我可以检索的实体,因为我可以在他们返回小提琴手看到...它只是它不会去当时的承诺,而不是它的土地在故障。

I enabled CORS by using the nightly build of ASP.NET Web API CORS support, it all works fine and I can retrieve the entities since I can see in fiddler that they are returned ... it's just that it doesn't go to the then promise instead it lands in fail.

更新:

在响应来自新创建的项目@Ward测试,我做了以下内容:

In response to @Ward testing from newly created projects I did the following:

项目1

创建了一个Web API项目。

Created a Web API Project.

这是新增的NuGet微软ASP.MET的Web API跨域资源共享(CORS)参考。

Added Microsoft ASP.MET Web API Cross-Origin Resource Sharing (CORS) Reference from Nuget.

增加了以下控制器:

namespace CORSBreezeTest1.Controllers
{
    public class ValuesController : EntitySetController<Value, int>
    {
        ValuesDbContext _context = new ValuesDbContext();

        [Queryable]
        public override IQueryable<Value> Get()
        {
            return _context.Values;
        }

        protected override Value GetEntityByKey(int key)
        {
            return _context.Values.Find(key);
        }

        protected override Value CreateEntity(Value entity)
        {
            Value value = _context.Values.Find(entity.Id);
            if (value != null)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Conflict));
            }
            _context.Values.Add(entity);
            _context.SaveChanges();
            return entity;
        }

        protected override int GetKey(Value entity)
        {
            return entity.Id;
        }

        protected override void Dispose(bool disposing)
        {
            _context.Dispose();
            base.Dispose(disposing);
        }
    }
}

和以下code第一个数据库:

And the following Code First Database:

namespace CORSBreezeTest1
{
    public class ValuesDbContext : DbContext
    {
        public ValuesDbContext()
            : base("DefaultConnection")
        {

        }

        public DbSet<Value> Values { get; set; }
    }

    public class Value
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }

        public string Name { get; set; }

        public int Quantity { get; set; }
    }
}

增加了以下行 WebApiConfig.cs

public static void Register(HttpConfiguration config)
{

 // Default code left out here ...

 config.Routes.MapODataRoute("Values", "odata", GetEdmModel());
 config.EnableQuerySupport();
 config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

}

private static IEdmModel GetEdmModel()
{
    ODataModelBuilder builder = new ODataConventionModelBuilder();
    builder.Namespace = "CORSBreezeTest1";
    builder.EntitySet<Value>("Values");
    return builder.GetEdmModel();
}

项目2个
然后创建另一个Web API项目。

PROJECT 2 Then created another Web API Project.

增加了的ASP.NET Web API项目的NuGet包微风

Added Breeze for ASP.NET Web API Projects Nuget Package

补充datajs的NuGet包。

Added datajs Nuget Package.

加code以下行 Index.cshtml

<p data-bind="visible: !results">Fetching data ... </p>
<ul data-bind="foreach: results, visible: results" style="display: none">
    <li>
        <span data-bind="text: Name"></span>
        <span data-bind="text: Quantity"></span>
    </li>
</ul>


@section Scripts {
    <script src="~/Scripts/knockout-2.2.0.debug.js"></script>
    <script src="~/Scripts/q.js"></script>
    <script src="~/Scripts/datajs-1.1.0.js"></script>
    <script src="~/Scripts/breeze.min.js"></script>
    <script type="text/javascript">
        $(function () {
            breeze.config.initializeAdapterInstances({ dataService: "OData" });
            var manager = new breeze.EntityManager("http://serverAddress/odata")
            var query = new breeze.EntityQuery.from("Values");
            manager.executeQuery(query).then(function (data) {
                ko.applyBindings(data);
            }).fail(function (e) {
                alert(e);
            });
        });
    </script>
}

由于测试是和它的工作,因为这两个网站都在本地主机。

Tested as is and it worked since both websites are on localhost.

发布项目1到Web服务器,以便测试将真正看到不同的起源,并进行测试。

Published PROJECT 1 to a web server so that the test will actually see different origins, and tested.

而这正是掘金看到:

第一个请求头是选项

OPTIONS /odata/Values HTTP/1.1

和第二个请求头是GET

And the second request headers are GET

GET /odata/Values HTTP/1.1

如果我改变我的失败 code为:

fail(function (e) {
 ko.applyBindings(e.body.value);
});

和我的淘汰赛code为:

And my knockout code to:

<p data-bind="visible: !$data">Fetching data ... </p>
<ul data-bind="foreach: $data, visible: $data" style="display: none">
    <li>
        <span data-bind="text: Name"></span>
        <span data-bind="text: Quantity"></span>
    </li>
</ul>

瞧!它来通过与数据:

Voila! It came through with the data:

这是什么控制台看到:

SEC7118: XMLHttpRequest for http://serverAddress/odata/$metadata required Cross Origin Resource Sharing (CORS). 
localhost:53317
SEC7119: XMLHttpRequest for http://serverAddress/odata/$metadata required CORS preflight. 
localhost:53317
SEC7118: XMLHttpRequest for http://serverAddress/odata/Values required Cross Origin Resource Sharing (CORS). 
localhost:53317
SEC7119: XMLHttpRequest for http://serverAddress/odata/Values required CORS preflight. 
localhost:53317
[Q] Unhandled rejection reasons (should be empty):Error: OK 

项目1安培; 2 使用 BreezeControllerAttribute

如果我在另一个试验中添加以下微风的NuGet例如一个新的控制器,并添加微风为的ASP.NET Web API项目的NuGet包,并添加以下控制器:

If I in another test add a new controller following Breeze Nuget example and add Breeze for ASP.NET Web API project Nuget package and add the following controller:

namespace CORSBreezeTest1.Controllers
{
    [BreezeController]
    public class BreezeValuesController : ApiController
    {
        readonly EFContextProvider<ValuesDbContext> _context =
            new EFContextProvider<ValuesDbContext>();

        [HttpGet]
        public string Metadata()
        {
            return _context.Metadata();
        }

        [HttpGet]
        public IQueryable<Value> Values()
        {
            return _context.Context.Values;
        }

        [HttpPost]
        public SaveResult SaveChanges(JObject saveBundle)
        {
            return _context.SaveChanges(saveBundle);
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }
    }
}

再修改客户端如下:

And then modify the client as following:

//breeze.config.initializeAdapterInstances({ dataService: "OData" });
var manager = new breeze.EntityManager("http://serverAddress/breeze/BreezeValues")

然后请求更改的:

Then the requests change:

和一切正常......我不知道,如果部分是什么, EntitySetController 修改<$ C $当不同的方式处理请求,或者是微风使不同的请求C>的DataService 。

And everything works ... I'm not sure if in part is something that EntitySetController handles requests differently or is Breeze making different requests when changing the dataService.

推荐答案

要得到它的工作的唯一方法是使用 BreezeControllerAttribute 来自的 Breeze.WebApi 以下使用API​​的微风确切方式。不使用 EntitySetController 键,回到普通的 ApiController 。在这个问题本身的详细解释。

The only way to get it to work was to use the BreezeControllerAttribute from Breeze.WebApi following the breeze exact way of using the api. Not using EntitySetController and going back to a regular ApiController. Detailed explanation in the question itself.

[BreezeController]
public class BreezeValuesController : ApiController
{
    // Methods here
}

这篇关于微风的executeQuery Q承诺失败CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆