asp.net-core - 如何在 asp.net 核心 MVC Controller 中使用 ReadAsStringAsync?

标签 asp.net-core asp.net-core-mvc

如何在 asp.net 核心 MVC Controller 中使用 ReadAsStringAsync?
Microsoft.AspNetCore.Mvc.Request 没有 Content 属性。有没有替代方法?谢谢!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using AuthLibrary;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;
using System.Threading.Tasks;

[Microsoft.AspNetCore.Mvc.Route("TestAPI")]
public class TestController : Controller
{

    [Microsoft.AspNetCore.Mvc.HttpPost]
    [AllowAnonymous]
    [Microsoft.AspNetCore.Mvc.Route("Start")]
      public async Task<HttpResponseMessage> Start()
    {
        string req = await this.Request.Content.ReadAsStringAsync();

        ////

    }
}

最佳答案

对于 Asp.Net Core MVC,您可以使用 request.Body 访问请求内容。 .

这是一个扩展:

public static class HttpRequestExtensions
{

    /// <summary>
    /// Retrieve the raw body as a string from the Request.Body stream
    /// </summary>
    /// <param name="request">Request instance to apply to</param>
    /// <param name="encoding">Optional - Encoding, defaults to UTF8</param>
    /// <returns></returns>
    public static async Task<string> GetRawBodyStringAsync(this HttpRequest request, Encoding encoding = null)
    {
        if (encoding == null)
            encoding = Encoding.UTF8;

        using (StreamReader reader = new StreamReader(request.Body, encoding))
            return await reader.ReadToEndAsync();
    }

    /// <summary>
    /// Retrieves the raw body as a byte array from the Request.Body stream
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public static async Task<byte[]> GetRawBodyBytesAsync(this HttpRequest request)
    {
        using (var ms = new MemoryStream(2048))
        {
            await request.Body.CopyToAsync(ms);
            return ms.ToArray();
        }
    }
}

利用:
public async Task<string> ReadStringDataManual()
{
    return await Request.GetRawBodyStringAsync();
}

引用:Accepting Raw Request Body Content in ASP.NET Core API Controllers

关于asp.net-core - 如何在 asp.net 核心 MVC Controller 中使用 ReadAsStringAsync?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56065605/

相关文章:

c# - 如何在 ASP.NET Core MVC 中获取文件的最后修改日期?

javascript - 在我的案例中,通过 JavaScript 从 EntityFramework 数据库获取数据的最佳和最有效的方法是什么?

asp.net-core - 通过 URL 访问 ASP.NET 5 View 组件

migration - WebApiCompatShim - 如何使用 MVC 6 配置 REST api

azure - Azure 云服务上的 Asp.Net Core MVC?

c# - .Net Core Integration TestServer 与 Generic IHostBuilder

asp.net-core - 基本bproject创建无法创建Prime Nuget缓存

azure - 正在为 Azure 应用服务中的多个虚拟应用程序配置 AspNetCoreModuleV2

asp.net - 发布期间的 ERROR_USER_NOT_AUTHORIZED_FOR_DBFULLSQL

asp.net-core - 在 asp.net 核心标识中更改电子邮件异步 "invalid token"