您希望可以在当前的 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 可能没有您所期望的。