首页 > 解决方案 > 如何从 ASP.NET Core 中的 Request.Body 读取参数

问题描述

上下文:我的应用程序位于中央登录应用程序后面,每当用户申请访问我的应用程序时,我的应用程序都会收到一个包含用户信息的 http 请求。我需要从 HttpRequest 正文中检索用户信息。

这是我到目前为止所尝试的:

currentContext.HttpContext.Request.Query["user-name"].toString();  // got nothing

using (var reader = new StreamReader(currentContext.HttpContext.Request.Body))
{
    var body = reader.ReadToEnd();
}   // I can get the raw HttpRequest Body as "user-name=some&user-email=something"

有什么方法可以用来解析 Request.Body 中的参数和值吗?我尝试了以下,也一无所获。

HttpContext.Item['user-name'] \\return nothing Request.Form["user-name"] \\ return nothing

我无法使用模型绑定的原因是,在 HttpRequest 正文中,键名是“用户名”,而在 c# 中,我无法创建带有“-”的变量

同时,在我的 .net 4.6 应用程序中,Request["KeyName"].toString()工作得很好。

标签: c#asp.net-corehttprequest

解决方案


我想出了一种将原始HttpRequest正文转换为查询字符串的方法,然后从中读取参数。

这是代码:

var queryString = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(requestBody);

string paramterValueIWant = queryString["KeyName"];

但是有一个问题,当KeyName体内不存在时,它会抛出异常。因此,您必须进行空检查或尝试捕获。

我仍然觉得应该有更好的方法来读取参数,正如我所提到的,在我的 .net 4.6 应用程序中,我需要做的就是Request["KeyName"].


推荐阅读