【问题标题】:My azure Http Trigger hitting an error because it isn't async. Why is my method not async?我的 azure Http Trigger 遇到错误,因为它不是异步的。为什么我的方法不是异步的?
【发布时间】:2020-04-09 19:25:46
【问题描述】:

我是 azure 新手,正在学习如何使用 HTTP 触发器。我已经使用 azure storage emulator 编写了一个在本地运行的简单函数

public static class Function1
    {
        [FunctionName("PutRecipeInCosmos")]
        public static async Task<HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] 
            HttpRequestMessage req, ILogger log)
        {
            return await Task.FromResult(req.CreateResponse(System.Net.HttpStatusCode.OK, "Hey!"));
        }
    }

当我点击这个函数是邮递员时,天蓝色控制台返回以下错误:

Microsoft.AspNetCore.Server.Kestrel.Core: Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true instead.

我的方法被标记为异步,并在返回时包含等待。为什么我会看到此错误?

****更新****

我通过返回一个返回 OKObjectResult 而不是 HttpResonseMesssage 来解决此问题。看来 HttpRequestMessage.Create 是一个同步 IO,不能异步处理?

public static class Function1
    {
        [FunctionName("PutRecipeInCosmos")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] 
            HttpRequestMessage req, ILogger log)
        {
            return new OkObjectResult("Hey!");
        }
    }

【问题讨论】:

  • 我认为错误与运行时有关,而不是与您的函数本身有关。能否请您更新功能工具? npm install -g azure-functions-core-tools
  • 谢谢,但是这个对我不起作用。我更新并重新启动了VS。 POST 出现同样的错误。
  • 这是 .net 核心吗?哪个版本?
  • netcoreapp3.0
  • 试试这个:npm install -g azure-functions-core-tools@3

标签: c# azure asynchronous .net-core


【解决方案1】:

编辑:

安装以下 NuGet 包:

Microsoft.Azure.Functions.Extensions Microsoft.NET.Sdk.Functions 包版本 1.0.28 或更高版本

然后,添加一个新的 Startup 类,其内容如下:

using System;
using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Http;
using Microsoft.Extensions.Logging;

[assembly: FunctionsStartup(typeof(MyNamespace.Startup))]

namespace MyNamespace
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
          builder.Services.Configure<KestrelServerOptions>(options =>
          {
              options.AllowSynchronousIO = true;
          });

          // If using IIS:
          builder.Services.Configure<IISServerOptions>(options =>
          {
              options.AllowSynchronousIO = true;
          });
        }
    }
}

【讨论】:

  • 我希望我的函数异步运行。但是,我确实尝试了您发布的第二个选项,但我仍然看到此错误
  • 我无法在我的机器上复制它。请尝试第一个选项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-24
  • 2015-07-21
  • 1970-01-01
  • 1970-01-01
  • 2019-06-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多