如何在 ASP.NET Core 中从 Request.Body 读取参数

Kun*_* Li 5 c# httprequest asp.net-core

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

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

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"
Run Code Online (Sandbox Code Playgroud)

有什么方法可以用来解析 Request.Body 中的参数和值吗?我尝试了以下操作,也没有得到任何结果。

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

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

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

Kun*_* Li 5

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

这是代码:

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

string paramterValueIWant = queryString["KeyName"];
Run Code Online (Sandbox Code Playgroud)

但有一个问题,当KeyName主体中不存在时,它会抛出异常。所以你必须进行空检查或尝试捕获。

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