我的答案是上述 Darin Dimitrov 的变体......所有 C# 变体(ASP.NET、Core、MVC 等)的变体答案应该是预期的......也许是 Visual Studio 的一年(2017 年、2019 年,等)...如果使用 Visual Basic 而不是 C#...
与 Anders Arpi 的评论类似,我无法使用所提供的 Darin 的答案(尽管显然我的答案是他的直接推导)。在我的情况下 Request.Properties 不是一个选项,但 Request.InputStream 是。我怀疑这在很大程度上取决于第一段中提到的项目类型。我的解决方案在 VS2017 中对我有用。
页面上也有类似的答案:How to get raw request body in ASP.NET?
但是,这些对我不起作用。但是,他们确实提供了重要的线索,例如“BeginRequest 事件中没有填充请求对象。您需要在事件生命周期的后期访问此对象'...
如果您在 HTTPRequests 构建/分析方面有经验,请跳过下一段。
尽管回想起来非常明显,但请求正文内容仅出现在某些 HTTPRequest 中。如果您只是在执行 GET(例如,单击导航选项卡将您带到一个新页面),您通常没有请求正文。因此,在测试解决方案时,请确保您正在查看应包含 RequestBody 的 HttpRequest。在我的例子中,任何实际从 UI 接收数据的提交按钮都将是一个包含 RequestBody 的帖子,因此存在(并且长度大于 0)。如果您没有 Fiddler 或 BurpSuite,或者正在使用 Shibboleth(这增加了 Fiddler/BurpSuite 测试的复杂性),您通常可以在 Firefox 开发人员工具中看到 HTTPRequest(通过 F12)......我在哪里调用请求正文将被称为参数和/或请求有效负载。
注意 Application_AuthenticateRequest 在 Global.asax.cs 中。
(in addition to other using statements)
using System.IO;
using System.Text;
using System.Web;
protected void Application_AuthenticateRequest(object sender, EventArgs e){
HttpApplication app = (HttpApplication)sender;
// Do a quick check to make sure that we are not on local.
// I've had some odd errors on local, though I suspect general implementation will not have this issue.
// So if we're actually on a 'real' (a.k.a. non-local) website, I do the following.
using (var stream = new MemoryStream())
{
app.Request.InputStream.Seek(0, SeekOrigin.Begin);
app.Request.InputStream.CopyTo(stream);
string requestBody = Encoding.UTF8.GetString(stream.ToArray());
app.Request.InputStream.Seek(0, SeekOrigin.Begin);
if (requestBody.Length > 0) Response.Write("requestBody: " + requestBody + "<br>");
}
}
请注意,我正在使用“Reinstate Monica Cellio”的建议在复制后重置 InputStream。