简体   繁体   English

如何在Azure移动应用服务中获取Cosmos Db数据

[英]How to Get Cosmos Db Data in Azure Mobile App Service

I try to get Data in Cosmos Db using Azure Mobile App Service , I tried this documentation https://docs.microsoft.com/en-us/azure/cosmos-db/sql-api-dotnet-application#_Toc395637765 but I can't implement it from MVC to Azure Mobile App Service , I'm still very new in ASP and don't realy understand all the function, in this Documentation they use this to get the data from it. 我尝试使用Azure Mobile App Service在Cosmos Db中获取数据,我尝试了此文档https://docs.microsoft.com/zh-cn/azure/cosmos-db/sql-api-dotnet-application#_Toc395637765但我可以从MVC到Azure Mobile App Service都没有实现它,我在ASP中还是一个新手,并不真正了解所有功能,在本文档中,他们使用它来从中获取数据。

public ActionResult Index()
{
    return View();
}

 [ActionName("Index")]
 public async Task<ActionResult> IndexAsync()
 {
     var items = await DocumentDBRepository<Item>.GetItemsAsync(d => !d.Completed);
     return View(items);
 } 

But because my ASP.NET is not MVC so I can't use ActionResult (my App Service will not have view) and that what make it confusing for me, I don't know how to return the task, and ussualy I'm using StreamReader to return the data but it says my Task doesn't contain StreamReader 但是因为我的ASP.NET不是MVC,所以我不能使用ActionResult (我的App Service无法查看),而这让我感到困惑,所以我不知道如何返回任务,通常我使用StreamReader返回数据,但它说我的任务不包含StreamReader

This is the DocumentDB class which handle the GetData : 这是处理GetDataDocumentDB类:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.Documents.Linq;

namespace gumilangService.Controllers
{
    public static class DocumentDBRepository<T> where T : class
    {
        private static readonly string DatabaseId = ConfigurationManager.AppSettings["database"];
        private static readonly string CollectionId = ConfigurationManager.AppSettings["collection"];
        private static DocumentClient client;

        public static void Initialize()
        {
            client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["endpoint"]), ConfigurationManager.AppSettings["authKey"]);            
        }

        public static async Task<IEnumerable<T>> GetItemsAsync(Expression<Func<T, string>> predicate)
        {
            IDocumentQuery<T> query = client.CreateDocumentQuery<T>(
                UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId))
               // .Where(predicate)
                .AsDocumentQuery();

            List<T> results = new List<T>();
            while (query.HasMoreResults)
            {
                results.AddRange(await query.ExecuteNextAsync<T>());
            }

            return results;
        }  
    }
}

And this is my Controller so far: 到目前为止,这是我的控制器:

public  string Get()
{
    var items =  DocumentDBRepository<MyCollection>.GetItemsAsync(d => d.Id);
    /*  using (var streamReader = new StreamReader(items.GetResponseStream()))
              {
                  var result = streamReader.ReadToEnd();
                  return result;
              }
    */
    return items.ToString();
    //return "Hello";    
}

And it return this instead the data: 然后返回此数据:

System.Threading.Tasks.Task`1[System.Collections.Generic.IEnumerable`1[gumilangService.DataObjects.MyCollection]]

Any idea how to implement this and get the data when I try it in Postman ? 我在Postman中尝试时如何实现它并获取数据?

You need to go back a bit further. 您需要再返回一点。

Your Get() method in the "controller" returns a string - it needs to return the actual data. 您在“控制器”中的Get()方法返回一个字符串-它需要返回实际数据。 ASP will serialize that data into a string using either XML or JSON. ASP将使用XML或JSON将数据序列化为字符串。

public MyItem Get(string id){
    Item item = DocumentDBRepository<MyItem>.Get(x => x.Id == id);
    return item; // separate line so you can put a breakpoint here and look
}

You used an async method 您使用了异步方法

var items =  DocumentDBRepository<MyCollection>.GetItemsAsync(d => d.Id);

which returns Task. 返回Task。 The correct way to call async methods is to make your own method async by replacing its return type with "async Task" and adding "await" before all async calls to other methods: 调用异步方法的正确方法是使自己的方法异步,方法是将其返回类型替换为“异步任务”,并在所有对其他方法的异步调用之前添加“等待”:

 var items =  await DocumentDBRepository<MyCollection>.GetItemsAsync(d => d.Id);

This is likely not the only issue... I strongly recommend that you download some sample project and understand how it works. 这可能不是唯一的问题...我强烈建议您下载一些示例项目并了解其工作方式。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM