简体   繁体   中英

reading the content of a request - ReadAsStringAsync()

I'm attempting to read the content of the request like so:

var translation = await req.Content.ReadAsStringAsync();

But getting this exception:

在此处输入图片说明

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?)

Here are the libraries I am using:

在此处输入图片说明

What am I doing wrong? How can I read the body of the content?

Here's the surrounding code:

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

As @Garr mentioned, Content is a property of HttpRequestMessage. In v2 Functions which targets at .NET Core 2, we usually use HttpRequest and read content as below.

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

Update

Runtime 2.0.12265 has been available to VS users, feel free to use .NET Core 2.2.


Also note that .NET Core 2.2 is supported since runtime v2.0.12265 but the runtime update has not been rolled out everywhere, ie we still consume the old one locally. So revert Microsoft.AspNetCore.Mvc package to 2.1.0 or we may get error. ( Microsoft.AspNetCore.Http is referenced by Microsoft.NET.Sdk.Functions hence no need to install again)

Your project file(Right click on project, Edit <FunctionProjectName>.csproj ) should look like this

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM