Как получить записи из таблицы Azure, привязанной к функции хранения Azure, используя REST API? - PullRequest
0 голосов
/ 25 апреля 2020

При извлечении записей из существующей таблицы хранения Azure (интегрированной с функцией Azure) я получаю следующую ошибку компиляции в редакторе портала Azure.

Сообщение об ошибке :

2020-04-23T17:05:36.870 [Information] Executing 'Functions.entry' (Reason='This function was programmatically called via the host APIs.', Id=8a9a5688-2dbf-4737-80ff-2a37f1c3a089)
2020-04-23T17:05:36.918 [Error] Function compilation error
Microsoft.CodeAnalysis.Scripting.CompilationErrorException : Script compilation failed.
   at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.CreateFunctionTarget(CancellationToken cancellationToken) at C:\azure-webjobs-sdk-script\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 314
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at async Microsoft.Azure.WebJobs.Script.Description.FunctionLoader`1.GetFunctionTargetAsync[T](Int32 attemptCount) at C:\azure-webjobs-sdk-script\src\WebJobs.Script\Description\FunctionLoader.cs : 55
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.GetFunctionTargetAsync(Boolean isInvocation) at C:\azure-webjobs-sdk-script\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 183
2020-04-23T17:05:37.000 [Error] run.csx(45,27): error CS1061: 'HttpMethod' does not contain a definition for 'method' and no extension method 'method' accepting a first argument of type 'HttpMethod' could be found (are you missing a using directive or an assembly reference?)
2020-04-23T17:05:37.030 [Error] run.csx(47,11): error CS1061: 'HttpMethod' does not contain a definition for 'method' and no extension method 'method' accepting a first argument of type 'HttpMethod' could be found (are you missing a using directive or an assembly reference?)
2020-04-23T17:05:37.060 [Error] run.csx(52,49): error CS1061: 'HttpMethod' does not contain a definition for 'Body' and no extension method 'Body' accepting a first argument of type 'HttpMethod' could be found (are you missing a using directive or an assembly reference?)
2020-04-23T17:05:37.101 [Error] Executed 'Functions.entry' (Failed, Id=8a9a5688-2dbf-4737-80ff-2a37f1c3a089)
Script compilation failed.

Ниже указан мой код:

#r "Newtonsoft.Json" 
#r "Microsoft.WindowsAzure.Storage"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System.Net.Http;

 public class Entry
 {
            public string Id => Guid.NewGuid().ToString("n");
             .......
            public string RowKey => Id;          
}

public static async Task<IActionResult> Run( HttpMethod req, Newtonsoft.Json.Linq.JArray inputTable, IAsyncCollector<Entry> outputTable, ILogger log)  
{  
   log.LogInformation(req.method);

   if(req.method == "GET")
   {
       return (ActionResult) new OkObjectResult(inputTable);
   }  

   var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
   var entry = JsonConvert.DeserializeObject<Entry>(requestBody);

   if (entry != null)
   {
       await outputTable.AddAsync(entry);
       return (ActionResult) new OkObjectResult(entry);
   }

   return new BadRequestObjectResult("Invalid Entry request");
}

Чего мне не хватает?

1 Ответ

0 голосов
/ 27 апреля 2020

Вот с чем вы столкнулись:

enter image description here

Из вашей ошибки, я думаю, вам нужно сделать два шага, чтобы понять это.

Сначала убедитесь, что у вас установлено расширение, создайте файл function.proj в этом месте:

enter image description here

Function.proj :

<Project Sdk="Microsoft.NET.Sdk">
    <PropertyGroup>
        <TargetFramework>netcoreapp3.0</TargetFramework>
    </PropertyGroup>
    <ItemGroup>
        <PackageReference Include="WindowsAzure.Storage" Version="9.3.3" />
    </ItemGroup>
</Project>

Во-вторых, я думаю, что используемый вами сейчас метод неверен.

Ваша структура должна выглядеть следующим образом: (HttpMethod не имеет метода с именем 'method', только HttpRequest имеет, и имя метода должно быть «Метод»)

#r "Newtonsoft.Json" 
#r "Microsoft.WindowsAzure.Storage"

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System.Net.Http;

 public class Entry
 {
            public string Id => Guid.NewGuid().ToString("n");
            public string RowKey => Id;          
}

public static async Task<IActionResult> Run( HttpRequest req, ILogger log)  
{  
   log.LogInformation(req.Method);

   if(req.Method == "GET")
   {
       return new OkObjectResult("OKOK");
   }  

   var requestBody = await new StreamReader(req.Body).ReadToEndAsync();
   var entry = JsonConvert.DeserializeObject<Entry>(requestBody);

   if (entry != null)
   {

   }

   return new BadRequestObjectResult("Invalid Entry request");
}

И тогда он будет работать нормально:

enter image description here

...