c# - 读取请求的内容 - ReadAsStringAsync()

标签 c# asp.net-mvc azure .net-core azure-functions

我尝试像这样读取请求的内容:

var翻译=await req.Content.ReadAsStringAsync();

但出现此异常:

enter image description here

Severity Code Description Project File Line Suppression State Error CS1061 'HttpRequest' does not contain a definition for 'Content' and no accessible extension method 'Content' accepting a first argument of type 'HttpRequest' could be found (are you missing a using directive or an assembly reference?)

这是我正在使用的库:

enter image description here

我做错了什么? 如何阅读内容正文?

这是周围的代码:

    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "post", Route = "OnTranslateSingleHttpTriggered")] HttpRequest req,
        ILogger log)
    {
        var translation = await req.Content.ReadAsStringAsync();
        //do work
    }

最佳答案

正如 @Garr 提到的,Content 是 HttpRequestMessage 的一个属性。在针对.NET Core 2的v2 Functions中,我们通常使用HttpRequest并读取如下内容。

string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

更新

Runtime 2.0.12265已向VS用户开放,请放心使用.NET Core 2.2。

<小时/>

另请注意,自 runtime v2.0.12265 起支持 .NET Core 2.2但运行时更新尚未在所有地方推出,即我们仍然在本地使用旧版本。所以恢复Microsoft.AspNetCore.Mvc包裹至 2.1.0否则我们可能会得到错误。 ( Microsoft.AspNetCore.HttpMicrosoft.NET.Sdk.Functions 引用,因此无需再次安装)

您的项目文件(右键单击项目,Edit <FunctionProjectName>.csproj)应如下所示

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <AzureFunctionsVersion>v2</AzureFunctionsVersion>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.1.0" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.0.24" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
    <PackageReference Include="System.Data.DataSetExtensions" Version="4.5.0" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>

关于c# - 读取请求的内容 - ReadAsStringAsync(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54189988/

相关文章:

c# - 接口(interface)中缺少 async 关键字是否会破坏 C#5.0 中的 DI?

c# - 返回 Enumerable.Empty<T>().AsQueryable() 是个坏主意吗?

javascript - 第二次单击浏览器文件按钮时上传图像

Asp.net MVC VirtualPathProvider View 解析错误

node.js - 我在哪里可以看到本地主机上的控制台日志以及该功能何时部署?

azure - 命令 'Get-AzFunctionApp ' 在 Azure 自动化 Runbook 中不起作用

c# - 在带有 SSL 的 C# 中使用 WebClient,因此无法嗅探流量

c# - 使用 binaryformatter/deserialize 加载数据时检测损坏的文件

c# - ASP.NET MVC3 双重验证(逗号、点、空)

azure - Azure Web 应用服务上的 Flask + Bokeh 服务器