System.InvalidOperationException при попытке использовать имя привязки в качестве параметра в функции Azure - PullRequest
0 голосов
/ 02 января 2019

следуйте этому уроку chain-azure-functions-data-using-bindings , при использовании JavaScript это работает, однако создал новое приложение-функцию с .net в качестве стека времени выполнения, добавили необходимые сопоставления db cosmos,при отправке запроса GET с параметром запроса, например https://azurefuncurl? code = abc & id = docs appinsights показывает, что функция azure / host не запускается из-за System.InvalidOperationException

попытался просмотреть официальную документацию: azure-functions / configInput-Usage , не повезло

function.json

{
 "bindings": [
{
  "authLevel": "function",
  "name": "req",
  "type": "httpTrigger",
  "direction": "in",
  "methods": [
    "get",
    "post"
  ]
},
{
  "name": "$return",
  "type": "http",
  "direction": "out"
},
{
  "type": "cosmosDB",
  "name": "bookmark",
  "databaseName": "func-io-learn-db",
  "collectionName": "Bookmarks",
  "connectionStringSetting": "chainazurefunctions_DOCUMENTDB",
  "id": "{id}",
  "partitionKey": "{id}",
  "direction": "in"
 }]
}

run.csx

#r "Newtonsoft.Json"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;

public static async Task<IActionResult> Run(HttpRequest req, ILogger log, dynamic bookmark)
{

log.LogInformation("C# HTTP trigger function processed a request.");

string name = req.Query["id"];

string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;

return name != null
    ? (ActionResult)new OkObjectResult($"Hello, {name}")
    : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}

сообщение об исключении:

Error indexing method 'Functions.find-bookmark' Unable to resolve binding parameter 'id'. Binding expressions must map to either a value provided by the trigger or a property of the value the trigger is bound to, or must be a system binding expression (e.g. sys.randguid, sys.utcnow, etc.).

Ответы [ 2 ]

0 голосов
/ 02 января 2019

для будущих ссылок на основании рекомендации Джерри Лю , Мне пришлось заменить id на {Query.id} в function.json как значения примечаний в ключе id и partitionKey

{
  "type": "cosmosDB",
  "name": "bookmark",
  "databaseName": "func-io-learn-db",
  "collectionName": "Bookmarks",
  "connectionStringSetting": "chainazurefunctions_DOCUMENTDB",
  "id": "{Query.id}",
  "partitionKey": "{Query.id}",
  "direction": "in"
}

в run.csx

создайте класс модели POCO и используйте его в качестве параметра в методе Run, ниже показан весь файл run.csx

#r "Newtonsoft.Json"

using System.Net;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.Text;

public class Bookmark
{
    [JsonIgnore]
    public string id {get; set;}

    [JsonProperty(PropertyName ="url")]
    public string URL {get;set;}

}

public static HttpResponseMessage  Run(HttpRequest  req, ILogger log, Bookmark bookmark)
{
    log.LogInformation("C# HTTP trigger function processed a request.");

    if(bookmark == null)
    {        
        string id = req.Query["id"];
        log.LogInformation($"Bookmark item {id} not found");

        return new HttpResponseMessage(HttpStatusCode.NotFound)
        {
            Content = new StringContent($"{id} not found", Encoding.UTF8, "application/json")
        };
    }
    else
    {
        log.LogInformation($"Found item {bookmark.URL}");
        return new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new StringContent(JsonConvert.SerializeObject(bookmark), Encoding.UTF8, "application/json")
        };
    }
}
0 голосов
/ 02 января 2019

Просто замените {id} на {Query.id}, посмотрите csx sample .

...