【发布时间】:2022-12-25 22:51:42
【问题描述】:
我有一个非常简单的中间件:
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
if(await CheckIfRequestIsAuthorize(context))
{
await next.Invoke(context);
}
}
private async Task<bool> CheckIfRequestIsAuthorize(HttpContext context)
{
Console.WriteLine("Inside method");
string requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
dynamic tmp = JsonConvert.DeserializeObject(requestBody);
string sessionId = (string)tmp.sessionId;
if(sessionId == "string")
{
return true;
} else
{
return false;
}
}
// this is my controller and class
public class MyOwnRequest
{
public string SessionId { get; set; }
public string SpecialKey { get; set; }
}
[HttpPost]
public async Task<IActionResult> PostMethod([FromBody] MyOwnRequest myOwnRequest)
{
return Ok("It's okey");
}
当我发出请求时,出现错误: “输入不包含任何 JSON 标记。当 isFinalBlock 为真时,预期输入以有效的 JSON 标记开头。
Path: $ | LineNumber: 0 | BytePositionInLine: 0.
我发现问题出在这部分代码上,因为当我们这样做时:
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
string requestBody = await new StreamReader(context.Request.Body).ReadToEndAsync();
await next.Invoke(context);
}
这也引起了一个问题,也许有人有类似的问题?
身体:
{
"sessionId": "string",
"specialKey": "string"
}
编辑:
我发现我需要启用双重读取请求的正文。但我为什么要这样做?当一个方法在next.invoke之前时,它应该只被调用一次。
【问题讨论】:
-
你没有在读取流后调整指针的位置
标签: asp.net-core json-deserialization asp.net-core-middleware