var request = context.HttpContext.Request;
var stream = new StreamReader(request.Body);
var body = stream.ReadToEnd();
在ASP.NET核心中,多次读取正文请求似乎很复杂,但是,如果您的第一次尝试以正确的方式进行,那么下次尝试就可以了。
我读了几个翻转,例如通过替换正文流,但我认为以下是最干净的:
最重要的一点是
// Helper to enable request stream rewinds
using Microsoft.AspNetCore.Http.Internal;
[...]
public class EnableBodyRewind : Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
var bodyStr = "";
var req = context.HttpContext.Request;
// Allows using several time the stream in ASP.Net Core
req.EnableRewind();
// Arguments: Stream, Encoding, detect encoding, buffer size
// AND, the most important: keep stream opened
using (StreamReader reader
= new StreamReader(req.Body, Encoding.UTF8, true, 1024, true))
{
bodyStr = reader.ReadToEnd();
}
// Rewind, so the core is not lost when it looks the body for the request
req.Body.Position = 0;
// Do whatever work with bodyStr here
}
}
public class SomeController : Controller
{
[HttpPost("MyRoute")]
[EnableBodyRewind]
public IActionResult SomeAction([FromBody]MyPostModel model )
{
// play the body string again
}
}
然后可以在请求处理程序中再次使用正文。
在您的例子中,如果您得到一个空结果,这可能意味着主体已经在较早的阶段被读取。在这种情况下,您可能需要使用中间件(见下文)。
但是,如果处理大流,请小心,这种行为意味着所有内容都被加载到内存中,这在文件上传的情况下不应该触发。
public sealed class BodyRewindMiddleware
{
private readonly RequestDelegate _next;
public BodyRewindMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try { context.Request.EnableRewind(); } catch { }
await _next(context);
// context.Request.Body.Dipose() might be added to release memory, not tested
}
}
public static class BodyRewindExtensions
{
public static IApplicationBuilder EnableRequestBodyRewind(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
return app.UseMiddleware<BodyRewindMiddleware>();
}
}
知道如何正确设置控制器描述吗? 谢谢,马里奥
现在,我从Visual Studio 2015提供的默认ASP.NET核心Web应用程序项目模板开始,包括对单个用户帐户的身份验证。 大多数(如果不是所有)生成的控制器都返回视图,通常遵循以下模式: 此方法返回一个您可以看到的视图,当web客户机请求时,一切都很好。但是如果游戏正在向相同的方法发送请求呢?在这种情况下,需要一个JSON响应(不是view/html文档),我的问题是在ASP.NET核
如何在reactor netty服务器中读取请求正文?我想让请求主体确定响应的内容,但在示例代码中找不到这样的示例。 例外 block()/blockFirst()/blockLast()正在阻塞,这在线程reactor-http-nio-2中不受支持 调用者 卷曲http://127.0.0.1:45441/test1/test-d“12312321312”-i-H“内容类型:应用程序/json
问题内容: 我现在使用的代码: 似乎工作正常,但我不确定在将ByteBuffer返回池之前是否需要ByteBuffer。我什至不确定要使用。文档中没有太多关于它的内容。 问题答案: 读取请求正文的一种更简单的方法是将其分派到一个工作线程,该工作线程可以使用。 有两种方法:使用或文档中所示的调度模式。这是使用的示例: 在基本上没有派遣你。