c# - 如何从 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()
工作得很好。
解决方案
我想出了一种将原始HttpRequest
正文转换为查询字符串的方法,然后从中读取参数。
这是代码:
var queryString = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(requestBody);
string paramterValueIWant = queryString["KeyName"];
但是有一个问题,当KeyName
体内不存在时,它会抛出异常。因此,您必须进行空检查或尝试捕获。
我仍然觉得应该有更好的方法来读取参数,正如我所提到的,在我的 .net 4.6 应用程序中,我需要做的就是Request["KeyName"]
.
推荐阅读
- swift - 如何通过 id Swift 获取数据
- mysql - 使用 bash 的 mysql 数据库复制脚本
- sql - 基于 IS_MEMBER 函数的行级安全性
- c# - 使用 DownloadUrl 在 C# 中下载文件
- python - 如何在 python 中包含 KNN 的混淆矩阵?
- arrays - 简单的 Spinner 数组未显示
- python - 如何从较大列表中的较小列表中删除项目?
- wordpress - WooCommerce 删除了除 1 个变量产品之外的所有产品文件
- python - 气流错误 - 得到一个意外的关键字参数“min”
- amazon-web-services - AWS Sagemaker 笔记本卡在待处理状态