简体   繁体   English

使用Ember从ASP.NET Web API调用HTTP方法GET

[英]Calling HTTP method GET from an ASP.NET Web API using Ember

I'm building an API in ASP.NET and I'm trying to call it with Ember... what I'm trying to get to work right now is the simple GET (find all). 我正在ASP.NET中构建一个API,并且试图用Ember来调用它……我现在想要开始工作的是简单的GET(查找全部)。

The output from postman (chrome extension for testing APIs) gives me this: postman的输出(用于测试API的chrome扩展)给了我:

[
    {
        "Id": 1,
        "Name": "psilva",
        "Project": "a",
        "Objectives": "s",
        "City": "a",
        "Country": "s",
        "EventStart": "2015-02-06T11:06:23.673",
        "Departure": "2015-02-06T11:06:23.673",
        "Arrival": "2015-02-06T11:06:23.673",
        "Registration": "a",
        "NationalTransportation": "a",
        "Accommodation": "a",
        "AcNumberNights": 1,
        "AcPreferHotel": "a",
        "AcPreferHotelUrl": "a",
        "Flight": "a",
        "FlDeparture": "2015-02-06T11:06:23.673",
        "FlDepartPrefer": "a",
        "FlDepartPreferUrl": "a",
        "FlReturn": "2015-02-06T11:06:23.673",
        "FlRetPrefer": "a",
        "FlRetPreferUrl": "a",
        "Notes": "a",
        "Files": "a",
        "Status": "a"
    },
    {
        "Id": 2,
        "Name": "psilva",
        "Project": "a",
        "Objectives": "s",
        "City": "a",
        "Country": "s",
        "EventStart": "2015-02-06T11:06:23.673",
        "Departure": "2015-02-06T11:06:23.673",
        "Arrival": "2015-02-06T11:06:23.673",
        "Registration": "a",
        "NationalTransportation": "a",
        "Accommodation": "a",
        "AcNumberNights": 1,
        "AcPreferHotel": "a",
        "AcPreferHotelUrl": "a",
        "Flight": "a",
        "FlDeparture": "2015-02-06T11:06:23.673",
        "FlDepartPrefer": "a",
        "FlDepartPreferUrl": "a",
        "FlReturn": "2015-02-06T11:06:23.673",
        "FlRetPrefer": "a",
        "FlRetPreferUrl": "a",
        "Notes": "a",
        "Files": "a",
        "Status": "a"
    },
    {
        "Id": 3,
        "Name": "psilva",
        "Project": "a",
        "Objectives": "s",
        "City": "a",
        "Country": "s",
        "EventStart": "2015-02-06T11:06:23.673",
        "Departure": "2015-02-06T11:06:23.673",
        "Arrival": "2015-02-06T11:06:23.673",
        "Registration": "a",
        "NationalTransportation": "a",
        "Accommodation": "a",
        "AcNumberNights": 1,
        "AcPreferHotel": "a",
        "AcPreferHotelUrl": "a",
        "Flight": "a",
        "FlDeparture": "2015-02-06T11:06:23.673",
        "FlDepartPrefer": "a",
        "FlDepartPreferUrl": "a",
        "FlReturn": "2015-02-06T11:06:23.673",
        "FlRetPrefer": "a",
        "FlRetPreferUrl": "a",
        "Notes": "a",
        "Files": "a",
        "Status": "a"
    },
    {
        "Id": 5,
        "Name": "psilva",
        "Project": "a",
        "Objectives": "s",
        "City": "a",
        "Country": "s",
        "EventStart": "2015-02-06T11:06:23.673",
        "Departure": "2015-02-06T11:06:23.673",
        "Arrival": "2015-02-06T11:06:23.673",
        "Registration": "a",
        "NationalTransportation": "a",
        "Accommodation": "a",
        "AcNumberNights": 1,
        "AcPreferHotel": "a",
        "AcPreferHotelUrl": "a",
        "Flight": "a",
        "FlDeparture": "2015-02-06T11:06:23.673",
        "FlDepartPrefer": "a",
        "FlDepartPreferUrl": "a",
        "FlReturn": "2015-02-06T11:06:23.673",
        "FlRetPrefer": "a",
        "FlRetPreferUrl": "a",
        "Notes": "a",
        "Files": "a",
        "Status": "a"
    }
]

Which means the API is working but calling it with Ember returns empty... I've been reading about this and what I think I have to do is tweak the Serializer and RESTAdapter, but I'm not sure how to use this... any ideas? 这意味着该API正在运行,但是用Ember调用将返回空...我一直在阅读有关此内容,我认为我需要做的是调整Serializer和RESTAdapter,但是我不确定如何使用它。 。 有任何想法吗?

Here's the Ember code: 这是Ember代码:

Model: 模型:

App.Event = DS.Model.extend({
    Id: DS.attr(),
    Name: DS.attr('string'),
    Project: DS.attr('string'),
    Objectives: DS.attr('string'),
    City: DS.attr('string'),
    Country: DS.attr('string'),
    EventStart: DS.attr('isodate'),
    Departure: DS.attr('isodate'),
    Arrival: DS.attr('isodate'),
    Registration: DS.attr('string'),
    NationalTransportation: DS.attr('string'),
    Accommodation: DS.attr('string'),
    AcNumberNights: DS.attr('number'),
    AcPreferHotel: DS.attr('string'),
    AcPreferHotelUrl: DS.attr('string'),
    Flight: DS.attr('string'),
    FlDeparture: DS.attr('isodate'),
    FlDepartPrefer: DS.attr('string'),
    FlDepartPreferUrl: DS.attr('string'),
    FlReturn: DS.attr('isodate'),
    FlRetPrefer: DS.attr('string'),
    FlRetPreferUrl: DS.attr('string'),
    Notes: DS.attr('string'),
    Files: DS.attr('string'),
    Status: DS.attr('string')
});

Controller: 控制器:

App.EventsController = Ember.ArrayController.extend({});

Route: 路线:

App.Router.map(function () {
    this.resource('sessions', function () {
        this.route('logout');
        this.route('login');
    });

    this.resource('help');

    this.resource('events', function () {
        this.route('list'),
        this.route('new'),
        this.route("event", { path: ":event_id" });
    });
});

App.EventsNewRoute = Ember.Route.extend({
    model: function (params) {
        return this.store.createRecord('event', params);
    }
});

App.EventsListRoute = Ember.Route.extend({
    controllerName: 'events',
    model: function () {
        return this.store.find("event");
    }
});

Index.html: index.html的:

<script type="text/x-handlebars" data-template-name="events/list">
        <section id="events">
            <div class="container-fluid">
                <div class="page-header">
                    <h1>Events Calendar</h1>
                </div>
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h2 class="panel-title">Events</h2>
                    </div>
                    <div class="panel-body">
                        {{#each event in events}}
                            {{#link-to "events.event"}}
                                <p>{{Name}}</p>
                            {{/link-to}}
                        {{else}}
                            <h2>No Events</h2>
                        {{/each}}
                    </div>
                </div>
            </div>
        </section>
    </script>

The Url I used in postman is: 我在邮递员中使用的网址是:

http://localhost:60590//api/Events HTTP://本地主机:60590 // API /活动

Adapter: 适配器:

App.ApplicationAdapter = DS.RESTAdapter.extend({
    host: 'http://localhost:60590/',
    namespace: 'api'
});

Serializer: 串行:

App.EventSerializer = DS.RESTSerializer.extend({
    /* add root element on incoming json */
    normalizePayload: function (payload) {
        return {event: payload};
    },
    /* remove root element from outgoing json */
    serializeIntoHash: function (hash, type, record, options) {
        Ember.merge(record.get("data"), this.serialize(record, options));
        Ember.merge(hash, record.get("data"));
    }
});

Error Message on console when I run: 运行时控制台上出现错误消息:

Error while processing route: events.list Assertion Failed: You must include an id for App.Event in a hash passed to push Error: Assertion Failed: You must include an id for App.Event in a hash passed to push 处理路线时出错:events.list断言失败:必须在传递给push的哈希中包含App.Event的id错误:断言失败:您必须在传递给push的哈希中包含App.Event的id

I've debugged it and found out that the response from the api is coming back correctly in json but it's the deserializer that's not working properly. 我调试了它,发现api的响应在json中正确返回了,但是解串器无法正常工作。

If you need any more information just ask, I really need to get this working ASAP, thanks. 如果你需要更多的信息,我真的需要尽快让这个工作,谢谢。

you should use the serializer. 您应该使用序列化器。 Try something like this: 尝试这样的事情:

App.EventSerializer = DS.RESTSerializer.extend({
  normalizePayload: function(payload) {
    return {
      "event": payload
    };
  }
});

That should help Ember to understand where your event model is in the response. 这应该可以帮助Ember了解event模型在响应中的位置。

The paths that Ember assumes by default will be: Ember默认采用的路径为:

  • GET /events for `store.find('event') GET /events for`store.find('event')
  • POST /events for store.createRecord('event', params) 用于store.createRecord('event', params) POST /events

Then, if you want to change that, you should implement the adapter: 然后,如果要更改它,您应该实现适配器:

App.EventAdapter = DS.RESTAdapter.extend({
  namespace: '/api',
  pathForType: function(type) {
    return 'Events';
  }
});

Let me know if it worked :) 让我知道它是否有效:)

I would highly recommend that you have your JSON response return a hash instead of an array. 我强烈建议您让JSON响应返回哈希而不是数组。 I believe Ember's RESTAdapter is expecting the JSON response to look like the following: 我相信Ember的RESTAdapter期望JSON响应如下所示:

{ 
  "events": [
    {
      "Id": 1,
      "Name": "psilva",
      "Project": "a",
      "Objectives": "s",
      "City": "a",
      "Country": "s",
...

The main advantage is that you can sideload records of different types, which many APIs end up doing to avoid the overhead of making multiple requests for resources, in addition to being a bit more explicit about exactly what you're returning with your response. 主要优点是您可以侧载不同类型的记录,许多API最终会这样做以避免产生多个资源请求的开销,此外还要更明确地了解您的响应返回的确切内容。

What was happening was that the model on the backend had it's properties starting with an uppercase letter and since Ember is used by conventions it wasn't connecting properly between the backend model and the frontend model. 发生的事情是后端的模型有一个以大写字母开头的属性,因为Ember被惯例使用,它在后端模型和前端模型之间没有正确连接。

Changing the backend properties to camelCase solved the problem. 将后端属性更改为camelCase解决了这个问题。

Moral of the story, always use camelCase when working with Ember. 故事的道德,在与Ember合作时总是使用camelCase。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从Angular调用时未获取所需的ASP.Net Web API方法 - Not getting the required ASP.Net web API method while calling from Angular AngularJS $ http使用参数中的对象访问ASP.NET Web Api - AngularJS $http get to ASP.NET Web Api with object in parameters 在AngularJS $ http中传递日期到ASP.NET Web Api - Passing Date in AngularJS $http get to ASP.NET Web Api 如何通过AngularJS $ http从ASP.Net Web API 2获取Access Token? - How to get Access Token from ASP.Net Web API 2 via AngularJS $http? 在ASP.NET Web API中添加额外的get方法 - Add an extra get method in asp.net web api 使用 jQuery 的 $.ajax() 方法的极其简单的 AJAX“HTTP GET”请求对我不起作用。 后端是 ASP.net WEB API controller - An extremely simple AJAX "HTTP GET" request using jQuery 's $.ajax() method does not Work for me. Backend is a ASP.net WEB API controller 从ASP.NET Web API返回的JavaScript数组未定义,GET方法 - JavaScript array undefined when returned from ASP.NET Web API, GET method 使用AngularJS从ASP.NET Web API方法下载文件 - Download file from an ASP.NET Web API method using AngularJS 使用 Axios post 方法从 Asp.Net Web API 下载 Excel - Excel download from Asp.Net Web API using Axios post method 从ASP.NET页中的Web Api Controller获得价值 - Get value from Web Api Controller in ASP.NET page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM