Azure http 函数和 DocumentDB

Azure http function and DocumentDB

正在尝试构建几个简单的 http Azure 函数。可以从 Web 应用程序中获取 POST,其中包含 JSON 正文,并将其作为文档保存在 CosmosDB (DocumentDB) 中。另一个发送带有参数的 GET 请求,该请求从数据库中读取该文档并将其 returns 作为 JSON.

我的 DocumentDB 集合已全部设置并准备就绪。

我发现每个接近的例子总是有一些细微的差别,比如输出到队列,所以这个例子不是我需要的。

你是在问你应该如何returnJSON?

这是我的一个 Azure Functions 的内容。首先,我尝试检索我想要的数据 (GetVotes())。之后,我将此数据更改为我想要 return 到客户端 (CreateResponse()) 和 return 到客户端的格式,同时将其序列化为 JSON.

    [FunctionName("Status")]
    public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter logWriter)
    {
        Status.log = logWriter;
        Status.log.Info("C# HTTP trigger function processed a request.");

        var votes = await GetVotes();
        var response = CreateResponse(votes);

        return req.CreateResponse(HttpStatusCode.OK, JsonConvert.SerializeObject(response));
    }

    private static List<ViewModel.Vote> CreateResponse(IEnumerable<Entities.Vote> votes)
    {
        var voteCount = new Dictionary<string, int>();
        foreach (var vote in votes)
        {
            Status.log.Info($"Found language `{vote.Language}`.");
            if (voteCount.ContainsKey(vote.Language))
            {
                voteCount[vote.Language]++;
            }
            else
            {
                voteCount.Add(vote.Language, 1);
            }
        }

        var result = new List<ViewModel.Vote>();
        foreach (var languageVotes in voteCount)
        {
            result.Add(new ViewModel.Vote(languageVotes.Key, languageVotes.Value));
        }
        return result;
    }

当然,您可以对任何类型的对象执行此操作,只要该对象可以序列化为 JSON。

此代码段的重要部分是 JsonConvert.SerializeObject(response),它实际序列化为 JSON 格式。

Trying to build a couple simple http Azure functions. One would take a POST from a web app, containing a JSON body, and save that as a document in CosmosDB (DocumentDB).

要从 HttpTrigger Azure 函数应用程序将数据存储在 Cosmos DB 中,您可以参考以下示例代码,在我这边工作正常。

using System.Net;

public static HttpResponseMessage Run(HttpRequestMessage req, out object taskDocument, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    MyData md=req.Content.ReadAsAsync<MyData>().Result;
    taskDocument  = new {
        name = md.name,
        task = md.task,
        duedate = md.duedate
    };


   if (name != "") {
        return req.CreateResponse(HttpStatusCode.OK);
    }
    else {
        return req.CreateResponse(HttpStatusCode.BadRequest);
    }
}

public class MyData{
    public string name { get; set;}
    public string task { get; set;}
    public string duedate { get; set;}
}

The other sends a GET request with a parameter, which reads that document from the database and returns it as JSON.

要通过 Azure Functions 应用从 Cosmos DB 检索数据并return将其作为JSON,请参考以下示例。

function.json

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "route": "documents/{name}"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "documentDB",
      "name": "inputDocument",
      "databaseName": "xxxdocumentdbtest",
      "collectionName": "testcoll",
      "sqlQuery": "SELECT * FROM c where c.name = {name}",
      "connection": "xxxx_DOCUMENTDB",
      "direction": "in"
    }
  ],
  "disabled": false
}

run.csx

#r "Newtonsoft.Json"
using System.Net;
using Newtonsoft.Json;

public static HttpResponseMessage Run(HttpRequestMessage req, IEnumerable<MyData> inputDocument, TraceWriter log)
{
    log.Info("C# HTTP trigger function processed a request.");

    MyData md = inputDocument.FirstOrDefault();

    log.Info(md.task);

    var val = JsonConvert.SerializeObject(md);

    return req.CreateResponse(HttpStatusCode.OK, val);
}

public class MyData{
    public string name { get; set;}
    public string task { get; set;}
    public string duedate { get; set;}
}