【问题标题】:How to use ReadAsStringAsync in asp.net core MVC controller?如何在 asp.net 核心 MVC 控制器中使用 ReadAsStringAsync?
【发布时间】:2019-09-27 15:43:13
【问题描述】:

如何在 asp.net core MVC 控制器中使用 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 asp.net-core-mvc


【解决方案1】:

您希望可以在当前的 MVC 请求上使用 .ReadAsStringAsync(),因为也许您已经看到过类似的内容?

using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Threading.Tasks;

namespace DL.SO.UI.Web.Controllers
{
    public class DashboardController : Controller
    {
        // In order to be able to inject the factory, you need to register in Startup.cs
        // services.AddHttpClient()
        //     .AddRouting(...)
        //     .AddMvc(...);
        private readonly IHttpClientFactory _httpClientFactory;

        public DashboardController(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public async Task<IActionResult> Index()
        {
            var client = _httpClientFactory.CreateClient();

            var request = new HttpRequestMessage(HttpMethod.Get, "https://www.google.com");

            var response = await client.SendAsync(request);
            if (response.IsSuccessStatusCode)
            {
                string bodyContent = await response.Content.ReadAsStringAsync();
            }

            return View();
        }
    }
}

这就是您使用HttpClient 在应用程序中获取外部数据/资源的方式。 .ReadAsStringAsync() 与 HttpContent 不同,这是 HttpRequestMessage 或 HttpResponseMessage 的属性。 HttpRequestMessage 和 HttpResponseMessage 都在 System.Net.Http 命名空间中。

但现在您已进入应用程序本身!事情有点不同。我们还没有对请求的响应(因为我们还没有完成return View();)。因此,我假设您要查看的内容是请求的内容?

GET 请求的内容

当 GET 请求进来时,MVC 会自动将请求的查询字符串绑定到控制器中的操作方法参数。它们也可以在当前 Request 对象的 Query 属性中使用:

public IActionResult Index(int page = 1, int size = 15)
{
    foreach (var param in Request.Query)
    {
        ...
    }

    return View();
}

POST 请求的内容

当 POST 请求进来时,Request.Body 可能并不总是有您要查找的数据。这取决于 POST 请求的内容类型。

默认情况下,当您提交表单时,请求的内容类型为 form-data。然后 MVC 会将输入绑定到您的视图模型作为操作参数:

[HttpPost]
public async Task<IActionResult> Close(CloseReservationViewModel model)
{
    Request.Form    // contains all the inputs, name/value pairs

    Request.Body    // will be empty!

    ...
}

如果您使用jQuery 触发POST 请求而不指定contentType,则默认为x-www-form-urlencoded:

@section scripts {
    <script type="text/javascript">
        $(function() {
            $.ajax({
                url: '@Url.Action("test", "dashboard", new { area = "" })',
                data: {
                    name: 'David Liang',
                    location: 'Portland Oregon'
                },
                method: 'POST'
            }).done(function (response) {
                console.info(response);
            });        
        });
    </script>
}
[HttpPost]
public async Task<IActionResult> Test()
{
    string body;
    using (var reader = new StreamReader(Request.Body))
    {
        body = await reader.ReadToEndAsync();
    }

    return Json(body);
}

结论

如果您想使用 HttpClient 调用 MVC 应用程序内部的外部服务,您可以使用来自 System.Net.Http 的 IHttpClientFactory、HttpClient 并从请求或响应中获取 HttpContent,而不会有太多麻烦.然后你可以做ReadAsStringAsync()关闭它。

如果您想查看从客户端发送到您的 MVC 应用程序的请求数据,MVC 已经做了很多工作来帮助您使用模型绑定来绑定数据。您还可以使用 StreamReader 读取 POST 请求的请求正文。请注意,这取决于内容类型,Request.Body 可能没有您所期望的。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2021-06-09
      • 1970-01-01
      • 2021-03-31
      • 1970-01-01
      • 1970-01-01
      • 2017-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多